前端实现流星迎面飞来
时间: 2023-06-29 14:05:41 浏览: 48
要在前端实现流星迎面飞来的效果,可以使用 HTML5 的 canvas 元素和 JavaScript 实现。
首先,需要在页面中创建一个 canvas 元素:
```html
<canvas id="canvas"></canvas>
```
然后,在 JavaScript 中获取 canvas 元素,并设置它的宽度和高度为浏览器窗口的宽度和高度:
```javascript
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
```
接着,定义一个 Meteor(流星)类,用于生成随机位置和速度的流星:
```javascript
function Meteor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.speed = Math.random() * 10 + 5;
}
```
然后,定义一个 drawMeteor(绘制流星)函数,用于绘制流星:
```javascript
function drawMeteor(meteor) {
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(meteor.x, meteor.y);
ctx.lineTo(meteor.x - 5, meteor.y + 20);
ctx.lineTo(meteor.x + 5, meteor.y + 20);
ctx.closePath();
ctx.fillStyle = "#fff";
ctx.fill();
}
```
最后,定义一个 animate(动画)函数,用于在 canvas 中不断绘制流星,并让它们向下飞行:
```javascript
function animate() {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < meteors.length; i++) {
drawMeteor(meteors[i]);
meteors[i].y += meteors[i].speed;
// 如果流星超出了屏幕,则重新生成一个随机位置和速度的流星
if (meteors[i].y > canvas.height) {
meteors[i] = new Meteor();
}
}
requestAnimationFrame(animate);
}
```
完整代码如下:
```html
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function Meteor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.speed = Math.random() * 10 + 5;
}
function drawMeteor(meteor) {
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(meteor.x, meteor.y);
ctx.lineTo(meteor.x - 5, meteor.y + 20);
ctx.lineTo(meteor.x + 5, meteor.y + 20);
ctx.closePath();
ctx.fillStyle = "#fff";
ctx.fill();
}
var meteors = [];
for (var i = 0; i < 10; i++) {
meteors.push(new Meteor());
}
function animate() {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < meteors.length; i++) {
drawMeteor(meteors[i]);
meteors[i].y += meteors[i].speed;
if (meteors[i].y > canvas.height) {
meteors[i] = new Meteor();
}
}
requestAnimationFrame(animate);
}
animate();
</script>
```