除了在角落里,为什么我的画布空白?

时间:2013-09-24 18:18:45

标签: javascript html canvas

我正在通过玩画布来学习JavaScript,我已经设法制作了一个随机生成颜色的正方形网格。

我决定让每个方块颜色增加和减少强度,但结果只是绘制网格的一个小角落,颜色不会改变。我做错了什么?

Online code herepaste bin here

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");

ctx.clearRect(0, 0, canvas.width, canvas.height);

function square(x, y) {
    this.x = x;
    this.y = y;
    this.sizex = 10;
    this.sizey = 10;
    this.Colo = Colo;

    function Colo() {
        var r = Math.floor(Math.random() * (255 - 1) + 1);
        var g = Math.floor(Math.random() * (255 - 1) + 1);
        var b = Math.floor(Math.random() * (255 - 1) + 1);
        var run = true;
        var rup, gup, bup = true;
        while (run) {

            if (rup) {
                if (r == 255) {
                    rup = false;
                } else if (r == 0) {
                    rup = true;
                }

                r += 1;
                r.toString();

            } else if (!gup) {
                r -= 1;
                r.toString();
            }

            if (gup) {
                if (g == 255) {
                    gup = false;
                } else if (g == 0) {
                    gup = true;
                }
                g += 1;
                g.toString();

            } else if (!gup) {
                g -= 1;
                g.toString();
            }

            if (bup = true) {
                if (b == 255) {
                    bup = false;
                } else if (b == 0) {
                    bup = true;
                }

                b += 1;
                b.toString();

            } else if (!gup) {
                b -= 1;
                b.toString();
            }

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            var col = "rgb(" + r + "," + g + "," + b + ")";

            return col;
            window.onfocus = function () {
                rup = true;
            };
            window.onblur = function () {
                isActive = false;
            };
            console.log("Ran loop.")
        }
    }

    ctx.fillStyle = Colo();
    ctx.fillRect(this.x, this.y, this.sizex, this.sizey);
}

var squares = new Array();
var p = 0;
for (var i = 0; i < 128; i++) {
    for (var j = 0; j < 72; j++) {
        p = i + j;
        squares[p] = new square(i * 10, j * 10);
    }
}

1 个答案:

答案 0 :(得分:3)

您的square()构造函数执行此操作:

ctx.fillStyle = Colo();
ctx.fillRect(this.x, this.y, this.sizex, this.sizey);

...其中Colo()除此之外还有:

ctx.clearRect(0, 0, canvas.width, canvas.height);

因此,在绘制每个矩形之前,您将清除整个画布。