-----------------------------------HTML-------------------------------------------
<!DOCTYPE html>
<html lang="zh-Hant-TW">
<head>
<title>TrackingMouse</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="TrackingMouseCss.css">
</head>
<body>
<div id="ball">
<div class="halo"></div>
<div class="halo"></div>
<div class="halo"></div>
</div>
<script type="text/javascript" src="TrackingMouseScript.js">
</script>
</body>
</html>
-----------------------------------CSS-------------------------------------------
:root{
--radius:40px;
--mouse-x;
--mouse-y;
--factor:1;
--scale;
}
body{
background-color: #000000;
}
#ball{
width: var(--radius);
height: var(--radius);
border-radius: 50%;
background-color:#FBD771;
position: absolute;
transform: translate(calc(var(--mouse-x) * 1px - var(--radius) / 2),calc(var(--mouse-y) * 1px - var(--radius) / 2));
}
.halo{
width: var(--radius);
height: var(--radius);
border-radius: 50%;
background-color: #FBD771;
opacity: 0.15;
position: absolute;
transform: scale(calc(var(--factor)* var(--scale))); /*放大*/
}
.halo:nth-of-type(1){
--factor:0.1;
}
.halo:nth-of-type(2){
--factor:0.3;
}
.halo:nth-of-type(3){
--factor:0.5;
}
-----------------------------------JS-------------------------------------------
var mouse_x = 0;
var mouse_y = 0;
var ball_x = 0;
var ball_y = 0;
var vel_x = 0;
var vel_y = 0;
const docStyle = document.documentElement.style;
const strength = 0.15;
const drag = 0.05;
document.addEventListener("mousemove",(event) =>{
// console.log(event.clientX);
// console.log(event.clientY);
mouse_x = event.clientX;
mouse_y = event.clientY;
});
function delayMotion() {
var distance_x = mouse_x - ball_x;
distance_x *= strength;
vel_x *= drag;
vel_x += distance_x;
ball_x += vel_x;
// console.log("distance_x:" , distance_x);
// console.log("mouse_x:" , mouse_x);
// console.log("ball_x:" , ball_x);
var distance_y = mouse_y - ball_y;
distance_y *= strength;
vel_y *= drag;
vel_y += distance_y;
ball_y += vel_y;
docStyle.setProperty("--mouse-x",ball_x);
docStyle.setProperty("--mouse-y",ball_y);
docStyle.setProperty("--scale", (vel_x + vel_y) * strength);
requestAnimationFrame(delayMotion);
}
delayMotion();
連結:https://wei.nidgetgod.net/TrackingMouse.html