代码
<canvas id="canv" width="400" height="400"></canvas>
<script>
var mov = true, raf = null;
var ctx = canv.getContext('2d');
class fiveStar {
constructor(cx,cy,r,fillcolor='yellow',strokecolor='red') {
this.cx = cx;
this.cy = cy;
this.r = r;
this.points = [];
this.keys = [0,2,4,1,3];
this.fillcolor = fillcolor;
this.strokecolor = strokecolor;
this.deg = 0;
};
create() {
for(let i = 0; i < 5; i ++) {
var x = this.cx + this.r * Math.cos((72 * i - this.deg) * Math.PI/180),
y = this.cy + this.r * Math.sin((72 * i - this.deg) * Math.PI/180);
this.points.push({x: x, y: y});
}
};
draw() {
ctx.beginPath();
this.points.forEach((_,key) => ctx.lineTo(this.points[this.keys[key]].x, this.points[this.keys[key]].y));
ctx.closePath();
ctx.lineWidth = 3;
ctx.strokeStyle = this.strokecolor;
ctx.fillStyle = this.fillcolor;
ctx.stroke();
ctx.fill();
};
rot() {
this.deg = (this.deg + 0.5) % 360;
ctx.save();
ctx.translate(this.cx, this.cy);
ctx.rotate(this.deg * Math.PI / 180);
ctx.translate(-this.cx, -this.cy);
star.draw();
ctx.restore();
};
};
var star = new fiveStar(200,200, 180);
star.create();
var render = () => {
if (mov) raf = requestAnimationFrame(render);
else cancelAnimationFrame(raf);
ctx.clearRect(0, 0, canv.width, canv.height);
star.rot();
};
render();
canv.onclick = () => {
mov = !mov;
render();
};
</script>
|