用canvas 画一个流星
时间: 2023-10-28 12:04:50 浏览: 39
以下是用canvas画一个流星的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas 流星</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = 200; // 流星起点x坐标
var y = 0; // 流星起点y坐标
var speed = 3; // 流星速度
var length = 50; // 流星长度
var angle = Math.PI/4; // 流星角度
var tailLength = 20; // 流星尾巴长度
function drawMeteor() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + Math.cos(angle) * length, y + Math.sin(angle) * length);
ctx.strokeStyle = "#fff";
ctx.lineWidth = 3;
ctx.stroke();
ctx.moveTo(x + Math.cos(angle) * tailLength, y + Math.sin(angle) * tailLength);
ctx.lineTo(x + Math.cos(angle) * length, y + Math.sin(angle) * length);
ctx.strokeStyle = "#ff0";
ctx.lineWidth = 1;
ctx.stroke();
x += Math.cos(angle) * speed;
y += Math.sin(angle) * speed;
if (y > canvas.height) { // 流星超出画布,重新生成流星
x = Math.random() * canvas.width;
y = 0;
length = Math.random() * 50 + 20;
angle = Math.PI/4 + Math.random() * Math.PI/4;
tailLength = length / 4;
}
requestAnimationFrame(drawMeteor); // 不断重绘
}
drawMeteor();
</script>
</body>
</html>
```
解释一下代码:
首先,创建一个canvas元素和一个绘图上下文对象ctx。
然后,定义一些变量,包括流星起点坐标、速度、长度、角度和尾巴长度。
接下来,定义一个绘制流星的函数drawMeteor。在该函数中,先清除画布,然后绘制流星的主体和尾巴,分别使用不同的颜色和线宽。接着,更新流星的坐标,并判断是否超出画布,如果超出,则重新生成一个流星。最后,使用requestAnimationFrame函数不断重绘流星。
最后,在页面加载完成后,调用drawMeteor函数绘制流星。