0

HTML5、JavaScript 和在画布中绘制多个矩形

所以我花了最后 2 个小时来困惑自己为什么这不起作用,我已经遵循了上述问题中的所有代码,但它仍然对我不起作用我做错了什么?

我添加了一个正方形以确保它到达那条线并实际工作

http://jsfiddle.net/Wh5YX/

function Shape(a,b,w,h,fill){

    this.a = a;
    this.b = b;
    this.w = w;
    this.h = h;
    this.fill = fill;

}

var canvas = document.getElementById("canvas");
if (canvas.getContext){
var myRect = [];

    myRect.push(new Shape(100, 0, 25, 25, "#333"));
    myRect.push(new Shape(0, 40, 39, 25, "#333"));
    myRect.push(new Shape(0, 80, 100, 25, "#333"));

ctx = canvas.getContext("2d");
for (i in myRect) {
    oblock = myRect[i];
    ctx.fillStyle = oblock.fill;
    ctx.fillRect(oblock.x,oblock.y,oblock.w,oblock.h);
    ctx.fillStyle="#CC00FF"; 
ctx.fillRect(100,100,20,20); 
}
}
4

1 回答 1

1

这似乎是Shape对象中的一个简单错字:

function Shape(a,b,w,h,fill){

    this.x = a; /// change to this.x
    this.y = b; /// change to this.y

    this.w = w;
    this.h = h;
    this.fill = fill;
}

在这里更新小提琴

或者您可以通过提供正确的变量名称来降低出现此类错误的风险(通常),例如:

function Shape(x, y, w, h, fill){

    this.x = x;  /// now we see the link more clearly
    this.y = y;

    this.w = w;
    this.h = h;
    this.fill = fill;
}
于 2013-10-12T01:31:14.860 回答