You can create an image dynamically without touching the DOM. But be aware of that image loading is asynchronous so you need to model your application to handle callbacks when image loaded (or failed or aborted).
For this reason you may want to consider an image loader if you are loading many images (see my profile for an example of one loader - there are more out there to suit your taste).
But in case you want to load the images yourselves - this is how you can do it:
// create the image element
var img = new Image;
// attach functions (callbacks) to handle image when loaded (or failed)
img.onload = myImageHandler;
img.onerror = myErrorHandler;
// set source last to start loading
img.src = myImageUrl;
Now the image will be loaded and myImageHandler()
will be called (assuming success). From here you continue your code:
function myImageHandler() {
// object 'this' represents the loaded image - use that if you load
// many images and share the handler
// draw image onto canvas (assuming ctx is defined as context)
ctx.drawImage(this, 0, 0);
// continue code from here...
}
I'm not showing the error-handler but it is basically the same as above just that you handle the error showing a message to user or have some fallback.
If you need to load many images you will need to keep track of the images loaded and not. It's fortunately not so much more complicated:
// setup array with URLs and one to hold the image objects
var imageURLs = [url1, url2, url, ...],
images = [],
count = imageURLs.length,
i = 0, url;
// define a common handler
function loaded() {
// decrease counter
count--;
// when 0 all images has loaded
if (count === 0) {
nextStepInCode(); // pseudo function
}
}
// invoke image loading:
for(; url = imageURLs[i++];) {
// create a new image and push to element stack
var img = new Image;
images.push(img);
// set handler
img.onload = loaded;
// invoke loading
img.src = url;
}
// code continues here before images has loaded, but you need
// to continue in the callback (loader)
Also here you need to add an error handler which also decrease the counter (or you won't be able to continue). An onabort
handler is also a pluss.
Hope this helps.