使用canvas绘制一个风车,并且能够转动

131 阅读1分钟

图01是绘制完成之后的效果图 image.png 图01

class Windmill {
    constructor(canvas, color, size) {
        this.canvas = canvas;
        this.color = color;
        this.size = size;
        this.ctx = canvas.getContext('2d');
        this.angle = 0;
    }
    draw() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.save();
        this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2);
        this.ctx.rotate((this.angle * Math.PI) / 180);
        let n = 2; //风叶的尺寸倍数
        // 绘制风车的四个叶片
        this.ctx.beginPath();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(50 * n, 10 * n);
        this.ctx.lineTo(50 * n, 50 * n);
        this.ctx.lineTo(10 * n, 50 * n);
        this.ctx.closePath();
        this.ctx.fillStyle = "red";
        this.ctx.fill();

        this.ctx.beginPath();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(-50 * n, 10 * n);
        this.ctx.lineTo(-50 * n, 50 * n);
        this.ctx.lineTo(-10 * n, 50 * n);
        this.ctx.closePath();
        this.ctx.fillStyle = "blue";
        this.ctx.fill();

        this.ctx.beginPath();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(-50 * n, -10 * n);
        this.ctx.lineTo(-50 * n, -50 * n);
        this.ctx.lineTo(-10 * n, -50 * n);
        this.ctx.closePath();
        this.ctx.fillStyle = "green";
        this.ctx.fill();

        this.ctx.beginPath();
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(50 * n, -10 * n);
        this.ctx.lineTo(50 * n, -50 * n);
        this.ctx.lineTo(10 * n, -50 * n);
        this.ctx.closePath();
        this.ctx.fillStyle = "yellow";
        this.ctx.fill();

        // 绘制风车的矩形中心轴
        // this.ctx.beginPath();
        // this.ctx.moveTo(-10, -10);
        // this.ctx.lineTo(10, -10);
        // this.ctx.lineTo(10, 10);
        // this.ctx.lineTo(-10, 10);
        // this.ctx.closePath();
        // this.ctx.fillStyle = "black";
        // this.ctx.fill();
        // this.ctx.restore();

        // 绘制风车的圆形中心轴
        this.ctx.beginPath();
        this.ctx.arc(0, 0, 10 * n, 0, 2 * Math.PI);
        this.ctx.fillStyle = "black";
        this.ctx.fill();

        this.ctx.restore();
    }
    update() {
        this.angle += 0.5;
        // this.angle += Math.random() * 10 - 5; // 抽风效果 每次旋转角度的增量是一个随机值
        this.draw();
        window.requestAnimationFrame(() => this.update());
    }
}