Html+ CSS + Java实现眼球跟随鼠标转动
代码存在一定的问题,可能会出现生活中的“斗鸡眼”,有兴趣的小伙伴可以看一下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background-color: rgb(236, 181, 79);
}
body{
display: flex;
justify-content: center;
align-items: center;
}
.my-eye{
width: 300px;
display: flex;
justify-content: space-between;
align-items: center;
}
.eye{
height: 100px;
width: 100px;
background-color: #fff;
border-radius: 100%;
box-shadow: 0 0 20px 1px rgba(236, 181, 79,1) inset,0 0 10px 0 rgba(44,41,41,.1);
position: relative;
}
.eye::after{
content: '';
position: absolute;
height: 30px;
width: 30px;
background-color: rgba(44,41,41);
border-radius: 100%;
border: 6px solid rgba(236, 181, 79,1);
top: calc(50% - 21px);
left: calc(50% - 21px);
box-shadow: 0 0 5px 0px rgba(236, 181, 79,0.5) inset,0 0 10px 0 rgba(44,41,41,.1);
}
</style>
</head>
<body>
<div class="my-eye">
<div class="eye"></div>
<div class="eye"></div>
</div>
<script>
document.onmousemove = function(e){
document.styleSheets[0].addRule(
`.eye::after`,
`top:15px ;left:15px;`
);
document.querySelectorAll('.eye').forEach(eye => {
//眼球相关属性
const boundingClientRect = eye.getBoundingClientRect();
const x = boundingClientRect.left + eye.offsetWidth / 2;
const y = boundingClientRect.top + eye.offsetHeight / 2;
//计算弧度
const radian = Math.atan2(e.clientX - x,e.clientY - y);
//计算角度
const angle = 270 - radian * (180 / Math.PI);
eye.style.cssText +=`
transform:rotate(${angle}deg);
`;
});
}
</script>
</body>
</html>
开头说的问题已经解决,把计算角度那里的270改成225(刚开始270的时候可以看出鼠标需要向右偏移45度,两眼球才能正对下方,改成180之后发现需要向左偏45度,综上改成225,完美解决此处bug)就正常了!