以下是关于 JavaScript 鼠标轨迹特效的相关内容:
基础概念: 鼠标轨迹特效是通过 JavaScript 监听鼠标的移动事件,并根据鼠标的坐标位置在页面上绘制出轨迹的视觉效果。
优势:
类型:
应用场景:
可能遇到的问题及原因:
解决方法:
以下是一个简单的鼠标轨迹特效示例代码:
<!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">
<style>
#canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawMouseTrack(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + 1, y + 1);
ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)';
ctx.lineWidth = 2;
ctx.stroke();
}
document.addEventListener('mousemove', throttle(drawMouseTrack, 50));
function throttle(func, delay) {
let timer = null;
return function (event) {
if (!timer) {
timer = setTimeout(() => {
func(event);
timer = null;
}, delay);
}
};
}
</script>
</body>
</html>
在上述示例中,通过节流函数限制了鼠标移动事件的触发频率,并在 canvas 上绘制鼠标轨迹。
领取专属 10元无门槛券
手把手带您无忧上云