能否实现双重Mouseover效果?鼠标轨迹喷溅与文字显示技术问询
实现鼠标喷溅显字效果的解决方案
要实现你需要的效果,核心逻辑很简单:
- 页面设为白色背景,居中放置白色文字(默认和背景同色,完全不可见)
- 让Canvas绝对定位覆盖整个页面,Canvas默认透明,鼠标移动时在上面绘制黑色喷溅轨迹
- 当黑色喷溅覆盖到白色文字区域时,白色文字在黑色背景的衬托下自然显现
下面是修改后的完整代码:
1. HTML 调整
添加居中的目标文字,调整页面结构:
<!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"> <title>Splatter Reveal Text</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1 style="color: black;">RENA</h1> <!-- 新增的居中显示文字 --> <div class="reveal-text">there's always more to see</div> <canvas id="my-canvas"></canvas> </body> </html>
2. CSS 样式(style.css)
设置页面背景、文字居中,以及Canvas的全屏覆盖定位:
* { margin: 0; padding: 0; box-sizing: border-box; } body { background-color: #fff; /* 白色背景 */ overflow: hidden; /* 避免出现滚动条 */ } .reveal-text { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; /* 白色文字,默认和背景融合 */ font-size: 2rem; font-family: sans-serif; z-index: 1; /* 文字在Canvas下方 */ } #my-canvas { position: fixed; top: 0; left: 0; z-index: 2; /* Canvas覆盖在文字上方 */ /* Canvas默认透明,不遮挡下方文字 */ }
3. JavaScript 微调
保留原喷溅逻辑,补充窗口大小变化时的Canvas适配:
const canvas = document.getElementById("my-canvas"); const ctx = canvas.getContext("2d"); // 初始化Canvas大小 function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } resizeCanvas(); // 窗口大小变化时重新调整Canvas尺寸 window.addEventListener('resize', resizeCanvas); // 存储喷溅粒子的数组 let atoms = []; canvas.addEventListener('mousemove', function(e){ for (let i = 0; i < 20; i++) { atoms.push(new Atom(e.x, e.y)); } }); const animate = () => { // 不需要清空Canvas,保留喷溅轨迹 atoms.forEach((atom, index) => { atom.draw(); atom.updateSpeed(); atom.updateSize(); if (atom.radius < 0.3){ atoms.splice(index, 1); } }) requestAnimationFrame(animate); } animate(); class Atom{ constructor(x,y){ this.x = x this.y = y this.radius = Math.random() * 8 + 2; this.speedX = Math.random() * 4 - 2; // 横向随机速度范围:-2 到 2 this.speedY = Math.random() * 4 - 2; // 纵向随机速度范围:-2 到 2 } updateSpeed(){ this.x += this.speedX; this.y += this.speedY; } updateSize(){ this.radius -= 0.1; } draw(){ ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); ctx.fillStyle = '#000'; // 明确设置黑色填充 ctx.fill(); } }
关键细节说明
- 文字显隐逻辑:白色文字和白色背景完全融合,只有当Canvas上的黑色喷溅覆盖时,白色文字才会在黑色背景的对比下显现。
- 层级关系:Canvas层级高于文字,确保喷溅轨迹绘制在文字上方,不会被文字遮挡。
- 窗口适配:新增的
resizeCanvas函数保证窗口大小变化时,Canvas始终覆盖整个页面。
内容的提问来源于stack exchange,提问作者Audrey
相关产品推荐
相关产品推荐

