HTML5, JavaScript and drawing multiple rectangles in a canvas

后端 未结 2 1874
慢半拍i
慢半拍i 2020-12-19 03:44

Why won\'t my multiple rectangles draw in the canvas?



  
    

        
相关标签:
2条回答
  • 2020-12-19 03:54

    Ok, so you were almost there. When you iterate round your array of rectangles, you are iterating over the array key not the objects themselves (see How to Loop through plain JavaScript object with objects as members?). Plus, as @jimjimmy1995 pointed out, you need to set the fill using .fillStyle as .fillRect does not have a fill parameter.

    This code will work:

    function Shape(x, y, w, h, fill) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fill = fill;
    }
    
    // get canvas element.
    var elem = document.getElementById('myCanvas');
    
    // check if context exist
    if (elem.getContext) {
    
        var myRect = [];
    
        myRect.push(new Shape(10, 0, 25, 25, "#333"));
        myRect.push(new Shape(0, 40, 39, 25, "#333"));
        myRect.push(new Shape(0, 80, 100, 25, "#333"));
    
        context = elem.getContext('2d');
        for (var i in myRect) {
            oRec = myRect[i];
            context.fillStyle = oRec.fill;
            context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-19 04:10

    Don't you need to give it the fill color?

    context.fillStyle = i.fill;
    context.fillRect(i.x,i.y,i.w,i.h);
    
    0 讨论(0)
提交回复
热议问题