在绘制鼠标轨迹时,如果希望影响画布后面的悬停元素,可以通过以下步骤实现:
mousemove
)和悬停效果。mousemove
事件。以下是一个简单的示例,展示如何在绘制鼠标轨迹时影响画布后面的悬停元素:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Trail Effect</title>
<style>
#canvas {
width: 100%;
height: 400px;
background-color: lightgray;
}
#hoverElement {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 150px;
left: 150px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="hoverElement"></div>
<script>
const canvas = document.getElementById('canvas');
const hoverElement = document.getElementById('hoverElement');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.addEventListener('mousemove', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Draw mouse trail
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
// Affect hover element
hoverElement.style.left = `${x - 50}px`;
hoverElement.style.top = `${y - 50}px`;
});
</script>
</body>
</html>
canvas
元素和一个div
元素(悬停元素)。mousemove
事件,获取鼠标在画布上的位置。requestAnimationFrame
优化重绘逻辑,减少不必要的绘制操作。let isDrawing = false;
canvas.addEventListener('mousedown', () => isDrawing = true);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mousemove', (event) => {
if (!isDrawing) return;
requestAnimationFrame(() => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
hoverElement.style.left = `${x - 50}px`;
hoverElement.style.top = `${y - 50}px`;
});
});
通过这种方式,可以在绘制鼠标轨迹的同时,动态影响画布后面的悬停元素,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云