html Canvas粒子文字特效
以下是一个简单的HTML Canvas粒子文字特效的示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Particle Text Effect</title>
<style>
canvas {
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const text = 'CODE';
const fontSize = 80;
const columns = canvas.width / fontSize;
const drops = [];
let font = 'Monaco';
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.font = `bold ${fontSize}px ${font}`;
function init() {
drops.length = 0;
for (let x = 0; x < columns; x++) drops[x] = 1;
}
function draw() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#0F0';
ctx.font = `bold ${fontSize}px ${font}`;
for (let i = 0; i < drops.length; i++) {
const text = text.charAt(Math.floor(Math.random() * text.length));
ctx.fillText(text, i * fontSize, drops[i] * fontSize);
if (drops[i] * fontSize > canvas.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
init();
setInterval(draw, 33);
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
init();
});
</script>
</body>
</html>
这段代码会在浏览器中创建一个Canvas元素,并显示一个随机文字粒子下落的动画效果。每个字母会以不同的速度下落,形成一种飘浮的视觉效果。当字母到达窗口的底部时,如果随机数大于0.975,则字母会重置到顶部。这个示例使用了setInterval
函数来定期重绘画布以实现动画效果。
评论已关闭