,可以通过以下步骤实现:
以下是一个示例代码,用于实现上述功能:
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
stroke: red;
stroke-width: 3px;
}
</style>
</head>
<body>
<svg id="svg" width="400" height="400">
<line id="line1" x1="100" y1="100" x2="300" y2="100" stroke="black" stroke-width="2"/>
<line id="line2" x1="100" y1="200" x2="300" y2="200" stroke="black" stroke-width="2"/>
<line id="line3" x1="100" y1="300" x2="300" y2="300" stroke="black" stroke-width="2"/>
</svg>
<script>
var svg = document.getElementById('svg');
var line1 = document.getElementById('line1');
var line2 = document.getElementById('line2');
var line3 = document.getElementById('line3');
svg.addEventListener('mousemove', function(event) {
var mouseX = event.clientX;
var mouseY = event.clientY;
var distance1 = getDistance(mouseX, mouseY, line1);
var distance2 = getDistance(mouseX, mouseY, line2);
var distance3 = getDistance(mouseX, mouseY, line3);
var minDistance = Math.min(distance1, distance2, distance3);
line1.classList.remove('highlight');
line2.classList.remove('highlight');
line3.classList.remove('highlight');
if (minDistance === distance1) {
line1.classList.add('highlight');
} else if (minDistance === distance2) {
line2.classList.add('highlight');
} else {
line3.classList.add('highlight');
}
});
function getDistance(x, y, line) {
var x1 = parseInt(line.getAttribute('x1'));
var y1 = parseInt(line.getAttribute('y1'));
var x2 = parseInt(line.getAttribute('x2'));
var y2 = parseInt(line.getAttribute('y2'));
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = dot / len_sq;
var xx, yy;
if (param < 0 || (x1 === x2 && y1 === y2)) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
return Math.sqrt(dx * dx + dy * dy);
}
</script>
</body>
</html>
在上述示例代码中,我们使用SVG绘制了三条线段,并为每条线段设置了id属性。通过监听SVG元素的mousemove事件,获取鼠标指针的坐标,并计算鼠标指针与每条线段的距离。最后,根据最小距离的边,添加或移除CSS类来突出显示最近的边。
请注意,这只是一个简单的示例,实际应用中可能需要根据具体需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云