canvas清除上一次画的_前端程序员,教你撩妹技能 get,用 canvas 画一场流星雨
时间: 2023-08-10 14:35:05 浏览: 43
好的,我可以帮你解决这个问题。
首先,我们需要在 HTML 中添加一个 canvas 元素,并设置其宽度和高度。然后在 JavaScript 中获取该 canvas 元素,并获取其上下文对象。
接下来,我们需要创建一个 Meteor 对象来表示一个流星。该对象应该有 x 和 y 坐标,以及速度和颜色等属性。
然后,我们可以使用 setInterval 函数来定时执行一个函数,该函数将在 canvas 上绘制所有的流星。在该函数中,我们可以先清除之前绘制的内容,然后遍历所有的流星对象并绘制它们。
以下是具体的实现代码,你可以参考一下:
HTML 代码:
```html
<canvas id="myCanvas" width="800" height="600"></canvas>
```
JavaScript 代码:
```javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
class Meteor {
constructor() {
this.x = Math.random() * canvas.width;
this.y = -50;
this.speed = Math.random() * 5 + 5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
move() {
this.y += this.speed;
this.x += this.speed / 2;
}
draw() {
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x + 20, this.y + 20);
ctx.stroke();
}
}
const meteors = [];
function createMeteor() {
const meteor = new Meteor();
meteors.push(meteor);
}
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < meteors.length; i++) {
const meteor = meteors[i];
meteor.move();
meteor.draw();
if (meteor.y > canvas.height + 50) {
meteors.splice(i, 1);
i--;
}
}
if (Math.random() < 0.1) {
createMeteor();
}
}, 30);
```
这样,我们就实现了一个简单的流星雨动画。希望能够帮到你!