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 に答える