返回
多彩代码,点亮天空,写出心中火焰
前端
2023-12-25 16:27:53
输出
我们都知道,一束小小的火苗,是微不足道的,随时可以被风吹灭。但当无数火苗聚集在一起时,就能形成熊熊烈火,势不可挡。
编程世界中,无数个代码块就像无数个火苗,看似微不足道,但当它们聚集在一起时,就能点亮整个世界。
今天,我们就用canvas来实现一个炫酷的烟花效果,将代码块化成艺术,让它在屏幕上绽放出绚丽的光彩。
步骤:
- 创建一个HTML文件,并引入canvas元素:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
- 在script.js文件中,首先获取canvas元素并获取它的上下文:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
- 设置画布的宽和高:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
- 创建一个粒子类:
class Particle {
constructor(x, y, vx, vy, radius, color) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = radius;
this.color = color;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
// 如果粒子超出画布范围,则反弹回来
if (this.x < 0 || this.x > canvas.width) {
this.vx = -this.vx;
}
if (this.y < 0 || this.y > canvas.height) {
this.vy = -this.vy;
}
}
}
- 创建一个粒子数组:
var particles = [];
- 在动画循环中,不断更新和绘制粒子:
function animate() {
requestAnimationFrame(animate);
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新和绘制粒子
for (var i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
}
}
- 当鼠标移动时,在鼠标位置创建新的粒子:
canvas.addEventListener('mousemove', function(e) {
var x = e.clientX;
var y = e.clientY;
var particle = new Particle(x, y, Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 5 + 1, 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')');
particles.push(particle);
});
运行代码,你就可以看到美丽的烟花效果了。随着鼠标的移动,无数个五彩缤纷的粒子从鼠标位置飞出,在屏幕上汇聚成绚丽的烟花。
这只是用canvas实现的一个简单的例子。你还可以根据自己的想象,创造出更多炫酷的代码艺术作品。