我正在尝试使用本教程使 svg 的眼睛瞳孔跟随光标:
https://dev.to/anomaly3108/make-svg-follow-cursor-using-css-and-js-2okp
我们有 4 个 div:
看起来 JS 正在工作,但角度不太准确。学生的位置太高,无法保持在正确的位置。
let eyeball_left = document.querySelector("#eyeball_left"),
pupil_left = document.querySelector("#pupil_left"),
eyeArea_left = eyeball_left.getBoundingClientRect(),
pupil_leftArea = pupil_left.getBoundingClientRect(),
R_left = eyeArea_left.width / 2,
r_left = pupil_leftArea.width / 2,
centerX_left = eyeArea_left.left + R_left,
centerY_left = eyeArea_left.top + R_left;
console.log(centerX_left)
console.log(centerY_left)
let eyeball_right = document.querySelector("#eyeball_right"),
pupil_right = document.querySelector("#pupil_right"),
eyeArea_right = eyeball_right.getBoundingClientRect(),
pupil_rightArea = pupil_right.getBoundingClientRect(),
R_right = eyeArea_right.width / 2,
r_right = pupil_rightArea.width / 2,
centerX_right = eyeArea_right.left + R_right,
centerY_right = eyeArea_right.top + R_right;
console.log(centerX_right)
console.log(centerY_right)
document.addEventListener("mousemove", (e) => {
let x_left = e.clientX - centerX_left,
y_left = e.clientY - centerY_left,
theta_left = Math.atan2(y_left, x_left),
angle_left = (theta_left * 180) / Math.PI + 360;
let x_right = e.clientX - centerX_right,
y_right = e.clientY - centerY_right,
theta_right = Math.atan2(y_right, x_right),
angle_right = (theta_right * 180) / Math.PI + 360;
pupil_left.style.transform = `translateX(${
R_left - r_left + "px"
}) rotate(${angle_left + "deg"})`;
pupil_left.style.transformOrigin = `${r_left + "px"} center`;
pupil_right.style.transform = `translateX(${
R_right - r_right + "px"
}) rotate(${angle_right + "deg"})`;
pupil_right.style.transformOrigin = `${r_right + "px"} center`;
});
#monster {
height: 100px;
width: 400px;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这里的基本思想是,我使用线条元素来决定眼睛的旋转/方向。一条线可以在两端和中间都有一个标记。在此示例中,眼球是一个标记,然后我根据鼠标的位置更新线的末端。
首先是一个带有轮廓的简单示例,然后是完整示例:
let l1 = document.querySelector("#l1"); let l2 = document.querySelector("#l2"); let svg1 = document.querySelector("#svg1"); const toSVGPoint = (svg, x, y) => { let p = new DOMPoint(x, y); return p.matrixTransform(svg.getScreenCTM().inverse()); }; document.addEventListener('mousemove', e => { let p = toSVGPoint(svg1, e.clientX, e.clientY); l1.setAttribute('x2', p.x); l1.setAttribute('y2', p.y); l2.setAttribute('x2', p.x); l2.setAttribute('y2', p.y); });let l1 = document.querySelector("#l1"); let l2 = document.querySelector("#l2"); let svg1 = document.querySelector("#svg1"); const toSVGPoint = (svg, x, y) => { let p = new DOMPoint(x, y); return p.matrixTransform(svg.getScreenCTM().inverse()); }; document.addEventListener('mousemove', e => { let p = toSVGPoint(svg1, e.clientX, e.clientY); l1.setAttribute('x2', p.x); l1.setAttribute('y2', p.y); l2.setAttribute('x2', p.x); l2.setAttribute('y2', p.y); });#monster { height: 100px; width: 400px; }