HTML5 打印矩形数组错误

HTML5 print array of rectangles error

本文关键字:数组 错误 打印 HTML5      更新时间:2023-09-26

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

这似乎是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;
}