Use a for loop to dynamically create an image drawn within a canvas

This is my code:

<canvas id="hour6" width="1024px" height="764px">
    <img id="hour6map" src=""/>
</canvas>

<canvas id="hour12" width="1024px" height="764px">
    <img id="hour12map" src=""/>
</canvas>

<canvas id="hour18" width="1024px" height="764px">
    <img id="hour18map" src=""/>
</canvas>

<canvas id="hour24" width="1024px" height="764px">
    <img id="hour24map" src=""/>
</canvas>

<canvas id="hour30" width="1024px" height="764px">
    <img id="hour30map" src=""/>
</canvas>

<canvas id="hour36" width="1024px" height="764px">
    <img id="hour36map" src=""/>
</canvas>

<canvas id="hour42" width="1024px" height="764px">
    <img id="hour42map" src=""/>
</canvas>

<canvas id="hour48" width="1024px" height="764px">
    <img id="hour48map" src=""/>
</canvas>

I need to be able to dynamically create all of these images within canvases using a for loop. Can anyone tell me how to use a for loop to generate all of these canvases with the images in them.

Upvotes: 0

Views: 186

Answers (1)

LostMyGlasses
LostMyGlasses

Reputation: 3144

You can try with this:

var canvas,
    img,
    index;

for (var i = 0; i < 8; i++) {
    index = 6 * (i + 1);
    canvas = document.createElement("canvas");
    canvas.id = "hour" + index;
    canvas.width = 1024;
    canvas.height = 764;
    img = document.createElement("img");
    img.id = "hour" + index + "map";
    img.src = "";
    canvas.appendChild(img);
    document.body.appendChild(canvas);
}

Upvotes: 3

Related Questions