效果图:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body,
html {
height: 100%;
}
body {
margin: 0;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.dot {
width: 20px;
height: 20px;
background: #208cf1;
border-radius: 50%;
position: relative;
margin-right: 50px;
}
.dot1 {
width: 20px;
height: 20px;
background: #f12043;
border-radius: 50%;
position: relative;
}
.dot1 .line1 {
background: #f12043;
}
.line,.line1 {
display: inline-block;
width: 20px;
height: 20px;
background: #208cf1;
position: absolute;
top: -10px;
transform-origin: 50% 100%;
clip-path: polygon(0% 100%,50% 0%,100% 100%);
}
</style>
</head>
<body>
<div class="dot">
<span class="line"></span>
</div>
<div class="dot1">
<span class="line1"></span>
</div>
</body>
<script>
function toLine() {
var dt = document.querySelector('.dot')
var dt1 = document.querySelector('.dot1')
var le = document.querySelector('.line')
var le1 = document.querySelector('.line1')
window.addEventListener("mousemove", function (e) {
//以 dt 标签为原点,相对于body的坐标位置
var x = (e.pageX - dt.offsetLeft - dt.offsetWidth / 2);
var y = (e.pageY - dt.offsetTop - dt.offsetHeight / 2);
//以 dt1 标签为原点,相对于body的坐标位置
var x1 = (e.pageX - dt1.offsetLeft - dt1.offsetWidth / 2);
var y1 = (e.pageY - dt1.offsetTop - dt1.offsetHeight / 2);
var ang = angle(0,0,x,y);
var ang1 = angle(0,0,x1,y1);
le.style.transform = `rotate(${ang}deg)`
le1.style.transform = `rotate(${ang1}deg)`
})
}
//旋转角度方法,px py 原点坐标 mx my 鼠标坐标
function angle(px,py,mx,my) {
var x = Math.abs(px-mx);
var y = Math.abs(py-my);
var z = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
var cos = y/z;
var radina = Math.acos(cos);//用反三角函数求弧度
var angle = Math.floor(180/(Math.PI/radina));//将弧度转换成角度
if(mx>px&&my>py){//鼠标在第四象限
angle = 180 - angle;
}
if(mx==px&&my>py){//鼠标在y轴负方向上
angle = 180;
}
if(mx>px&&my==py){//鼠标在x轴正方向上
angle = 90;
}
if(mx<px&&my>py){//鼠标在第三象限
angle = 180+angle;
}
if(mx<px&&my==py){//鼠标在x轴负方向
angle = 270;
}
if(mx<px&&my<py){//鼠标在第二象限
angle = 360 - angle;
}
return angle;
}
toLine()
</script>
</html>