簡體   English   中英

JavaScript畫布顏色屬性干擾

[英]JavaScript canvas color-property interference

問題:塊的顏色應該為灰色,但繼承了紅色的球的顏色屬性。 block2應該為藍色,但繼承了灰色的塊顏色。 我該如何解決這個問題? 我剛剛開始學習如何編程,所以我對這樣的事情沒有太多經驗:/

碼:

function Player(x, y, w, h, color) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.color = color;
    this.dy = 3;

    this.draw = function() {
        c.fillRect(this.x, this.y, this.w, this.h);
        c.fillStyle = this.color;
        c.stroke();
        c.closePath();
    };

    this.update = function() {
        if (keyW === true) {
            block.y -= block.dy;
        }
        if (keyS === true) {
            block.y += block.dy;
        }
        if (arrowUp === true) {
            block2.y -= block2.dy;
        }
        if (arrowDown === true) {
            block2.y += block2.dy;
        }


        if (this.y + this.h > canvas.height) {
            this.y = canvas.height - this.h;
        }
        if (this.y < 0) {
            this.y = 0;
        }

        this.draw();
    };
}
block = new Player(10, (canvas.height / 2) - 50, 250, 100, "grey");
block2 = new Player(canvas.width - 30, (canvas.height / 2) - 50, 20, 100, "blue");

function Ball(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
    this.dx = 3;
    this.dy = 0;

    this.draw = function() {
        c.beginPath();
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        c.fillStyle = this.color;
        c.fill();
        c.closePath();
    };

    this.update = function() {
        this.x -= this.dx;

        if (this.y + this.radius > canvas.height) {
            this.y = canvas.height - this.radius;
        }
        if (this.y - this.radius < 0) {
            this.y = this.radius;
        }
        if (this.x + this.radius > canvas.width) {
            this.dx = -this.dx;
        }
        if (this.x - this.radius < 0) {
            this.dx = -this.dx;
        }

        this.draw(); 
    };
}
ball = new Ball(canvas.width / 2 - 50, canvas.height / 2, 10, "red");

在更改顏色之前,您要在Player更新方法中填充一個rect,因此它使用以前的fillStyle值(紅色)。

代替:

c.fillRect(x, y, w, h);
c.fillStyle = this.color;

做:

c.fillStyle = this.color;
c.fillRect(x, y, w, h);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM