HTML5打印矩形矩阵错误

时间:2013-10-12 01:27:58

标签: javascript html5 canvas html5-canvas

HTML5, JavaScript and drawing multiple rectangles in a canvas

所以我花了最后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); 
}
}

1 个答案:

答案 0 :(得分: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;
}

<强> Updated fiddle here

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

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;
}