【发布时间】:2020-12-03 13:25:19
【问题描述】:
const initEyeMove = () => {
let eyeBall = document.querySelector(`.eyeball`);
let pupil = document.querySelector(`.pupil`);
if (eyeBall && pupil) {
let eyeArea = eyeBall.getBoundingClientRect();
let pupilArea = pupil.getBoundingClientRect();
let R = eyeArea.width / 2;
let r = pupilArea.width / 2;
let centerX = eyeArea.left + R;
let centerY = eyeArea.top + R;
document.addEventListener(`mousemove`, (e) => {
let x = e.clientX - centerX;
let y = e.clientY - centerY;
let theta = Math.atan2(y, x);
let angle = theta * 180 / Math.PI + 360;
if (angle < 330 || angle > 380) {
angle = 0;
}
pupil.style.transform = `translateX(${R - r + `px`}) rotate(${angle + `deg`})`;
pupil.style.transformOrigin = `${r + `px`} center`;
});
}
};
initEyeMove();
.pupil {
background-color: transparent;
width: 1px;
height: 1px;
border-radius: 50%;
}
.pupil svg {
top: 50%;
left: 50%;
transform: translate(30%, 30%);
}
.eye {
position: absolute;
top: 1px;
left: 6px;
}
.eyeball {
width: 10px;
height: 10px;
background-color: none;
position: absolute;
top: 120px;
left: 6px;
}
<div class="eyeball">
<div class="pupil">
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<style>
.cls-2{fill-rule:evenodd}
</style>
</defs>
<g id="Слой_2" data-name="Слой 2">
<g id="Слой_1-2" data-name="Слой 1">
<g id="Untitled">
<path fill="#ff0" fill-rule="evenodd" stroke="#ff0" stroke-linecap="round" stroke-linejoin="round" stroke-width="10" d="M5 71.4C5 34.7 37.3 5 77.1 5s72.1 29.7 72.1 66.4-32.3 66.4-72.1 66.4S5 108 5 71.4z"/>
<path d="M59.9 31.3a15.2 15.2 0 1115.2 15.2 15.19 15.19 0 01-15.2-15.2zM82 75.3c2.9-19.8 16.7-35.4 30.8-34.9s23.1 16.9 20.2 36.7-16.7 35.4-30.8 34.9S79.1 95.1 82 75.3z" class="cls-2"/>
</g>
</g>
</g>
</svg>
</div>
</div>
有一个 if 语句可以在特定条件下使 mousemove 上的元素的角度归零。 需要让它从超出设定条件之前的角度慢慢回零。
更新:添加了更多细节,希望这个眼睛能更平滑地回到起始位置,而不是在角度大于或小于需要时立即返回。
【问题讨论】:
标签: javascript if-statement animation mousemove decrement