I am trying to draw multiple images onto an HTML Canvas element.
assetData
is an array of objects, each containing the data required to write an image to the canvas, fetched from a database. Crucially, assetData
could be of any length: It could contain one image, or it could contain 100.
The code below does not work, as gfxCtx.drawImage()
draws the final image specified in the array multiple times, rather than each individual image.
for(var x = 0; x < assetData.length; x++) {
var layer = eval(assetData[x])
var gfx = new Image
gfx.src = "images/" + layer.src
gfx.onload = function() {
gfxCtx.drawImage(gfx, layer.x, layer.y, layer.w, layer.h)
compile()
}
}
compile()
handles drawing the images onto the canvas
If there were a fixed number of images to be drawn, I would assign each to a separate variable. In this instance, however, I do not necessarily know how many images are to be drawn, and I would like to keep the code fairly concise.
Is there a clean, straightforward solution to this problem?
Thanks!