效果图:
点上的线段跟踪元素移动,并且线会根据鼠标位置来连接元素的那个角
实现代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><style>* {padding: 0;margin: 0;}.piont {width: 10px;height: 10px;position: fixed;top: 300px;left: 600px;background-color: red;border-radius: 50%;}.line {height: 2px;width: 100px;position: fixed;top: 305px;left: 605px;transform-origin: top left;background-color: aqua;}.box {width: 100px;height: 100px;background-color: red;position: fixed;top: 0;left: 0;}</style>
</head><body><div class="piont"></div><div class="line"></div><div class="box"></div>
</body><script>let line = document.querySelector(".line")let box = document.querySelector(".box")let piont = document.querySelector(".piont")box.addEventListener("mousedown", function(e) {console.log(e.clientX)console.log(e.clientY)const disX = e.clientX - box.offsetLeftconst disY = e.clientY - box.offsetTopdocument.onmousemove = (e) => {// 通过事件委托,计算移动的距离// 左上角位置let left = e.clientX - disXlet top = e.clientY - disYlet pos = {lt: {left: left,top: top},// 右上角位置rt: {left: left + box.clientWidth,top: top},// 右下角位置rb: {left: left + box.clientWidth,top: top + box.clientHeight},// 左上角位置lb: {left: left,top: top + box.clientHeight}}// 设置当前元素box.style.cssText += `;left:${left}px;top:${top}px;`// 画线的位置和长度// 我们根据鼠标的位置来判断链接那个角let s = ""if (e.clientX > piont.offsetLeft) {s = "l"} else {s = "r"}if (e.clientY > piont.offsetTop) {s += "t"} else {s += "b"}let a = pos[s].left - piont.offsetLeftlet b = pos[s].top - piont.offsetToplet c = Math.sqrt(a ** 2 + b ** 2)let r = Math.atan2(b, a) * 180 / Math.PIconsole.log(r)line.style.transform = `rotate(${r}deg)`line.style.width = c + "px"}document.onmouseup = () => {document.onmousemove = nulldocument.onmouseup = null}})//已知直角三角形的斜角度数和斜边长度,求邻边和对边的长度function side_length(angle, long) {//获得弧度var radian = ((2 * Math.PI) / 360) * angle;return {opposite_side: Math.sin(radian) * long, //斜角对边长度adjacent_side: Math.cos(radian) * long //斜角邻边长度};}// 已知直角三角形的一直角边长度和斜边长度,求之间的角度function bevel(straight, oblique) {const sinOfAngleX = straight / oblique;const angle = Math.round((Math.asin(sinOfAngleX) * 180) / Math.PI);return angle;}
</script></html>