0

I have 4 bases all using the same image that I want to draw in a row across the screen. They are all canvases. I load the image and use the onload function and the canvas context to draw the image inside the onload function. The problem is, only the last one shows up with the image, the others are there, and I can print them to the console, but cannot see the images.

It is obviously something really simple but when you are stuck it sometimes is hard to see the obvious error.

Code:

function setup_bases(){

var top = 460;
var left = screen_left + 170;
var base_img_location = img_dir + "base.png";

var base;

for(c=0; c < 4; c++){
    var id= "base" + c;
    base = document.createElement('canvas');
    console.log("base = ")
    console.log(base);

    var ctx = base.getContext("2d");

    var rule = "#" + id + " { position: absolute; top: "+ top + "px; left: " + left + "px; width: 60px; height: 44px; }"
    stylesheet.insertRule(rule);

    base.setAttribute("id", id);
    base.setAttribute("class", "base");
    base.setAttribute("position", "absolute")
    base.setAttribute("width", "60px");
    base.setAttribute("height", "44px");
    base.style.left = left + "px";
    base.style.top = top + "px;"

    var img = new Image();
    img.onload = function(){
        ctx.drawImage(img,0,0);
    }
    img.src = base_img_location;        

    document.getElementById("main").appendChild(base);
    console.log(base)

    left += 230;

    console.log("img.src =");
    console.log(img.src);
  }
}
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
marienbad
  • 1,461
  • 1
  • 9
  • 19

0 Answers0