I'm trying to add a sprite to the canvas of my game. However, I don't want to use an image tag. However, I haven't found a way to do this no matter how hard I searched. Something like:
var image = 'sample.jpg'
draw(image)
I'm trying to add a sprite to the canvas of my game. However, I don't want to use an image tag. However, I haven't found a way to do this no matter how hard I searched. Something like:
var image = 'sample.jpg'
draw(image)
Philip's suggested improvement to DMGregory's answer is important.
//Create Image object
var image2 = new Image();
//Get context ready
var canvas2 = document.getElementById('mycanvasid');
var ctx2 = canvas2.getContext('2d');
//Now, set .onload with function(s) that require a loaded image, before setting .src
image2.onload = function () {
var x = 0, y = 0;
ctx2.drawImage(image2, x, y); //aka, ctx2.drawImage(this, 0, 0);
}
//Finally, start the loading process
image2.src = 'path/to/your/image.png';
Recapping the doc examples discussed in the comments above:
// First, create a reference to the image we want to draw.
var image = new Image(); // or document.createElement('img');
image.src = 'path/to/your/image.png';
// Next, find (or create/add) our canvas, and get its drawing context.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Finally, draw our image onto the canvas with a given x & y position.
var x = 0, y = 0;
ctx.drawImage(image, x, y);
ctx.drawImage call in the .onload handler of the image. Otherwise the image will very likely be drawn before it is loaded, resulting in drawing nothing at all.
\$\endgroup\$