function Star(x, y, rotation) {
this.x = x;
this.y = y;
this.length = 15;
this.scaleX = 1;
this.scaleY = 1;
this.rotation = rotation;
this.angle = Math.random() * 360;
this.vx = 0;
this.vy = 0;
this.alpha = 0.6;
this.color = `rgb(${Math.random() * 250},${Math.random() * 250},${Math.random() * 250})`;
}
Star.prototype.draw = function(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(24, 0);
ctx.lineTo(24, 24);
ctx.lineTo(0, 24);
ctx.closePath();
ctx.scale(this.scaleX, this.scaleY);
ctx.strokeStyle = 'rgba(0,0,0,0)';
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.miterLimit = 4;
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.moveTo(12, 0.89);
ctx.lineTo(15.609, 8.204);
ctx.lineTo(23.682, 9.377);
ctx.lineTo(17.842, 15.071);
ctx.lineTo(19.22, 23.11);
ctx.lineTo(12, 19.315);
ctx.lineTo(4.78, 23.11);
ctx.lineTo(6.159, 15.071);
ctx.lineTo(0.318, 9.377);
ctx.lineTo(8.39, 8.204);
ctx.lineTo(12, 0.89);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
ctx.restore();
};
export default Star;
以上代码可以在画布上创建一个星星
<template>
<div class="star-wrap">
<canvas ref="canvas" width="1000" height="100"></canvas>
</div>
</template>
<script>
import Star from "@/common/Star.js";
export default {
name: "flystars",
data() {
return {
line: 0,
stars: [],
W: 600,
H: 100
};
},
mounted() {
this.start();
},
methods: {
start() {
this.line = 0;
this.drawFrame();
},
animateLine() {
let star;
this.stars.push(new Star(this.line, this.H / 2, Math.random() * 360));
this.line += this.W / 60;
},
moveStars() {
let ctx = this.$refs.canvas.getContext("2d");
this.stars.forEach(star => {
if (star.scaleX <= 1 && star.scaleX > 0) {
star.scaleX -= 0.02;
star.scaleY -= 0.02;
}
if (star.alpha >= 0.05) {
star.alpha -= 0.01;
} else if (star.alpha < 0.1) {
this.stars.splice(star, 1);
}
star.vx = Math.sin(star.angle) * 0.8;
star.vy = Math.cos(star.angle) * 0.8;
// star.angle += 0.1;
star.x += star.vx - 2;
star.y += star.vy;
star.draw(ctx);
});
},
drawFrame() {
if (this.line < this.W * 3) {
window.requestAnimationFrame(this.drawFrame);
}
let ctx = this.$refs.canvas.getContext("2d");
ctx.clearRect(0, 0, this.W, this.H);
this.animateLine();
this.moveStars();
}
}
};
</script>
<style>
.star-wrap {
width: 200px;
overflow: hidden;
}
</style>
以上代码是引用Star.js 动态创建多个星星并实现一划而过的效果