# How to draw an image on canvas without html

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)

• You've consulted the docs for canvas.getContext('2d').drawImage? Oct 12 '16 at 23:34
• Yes but that requires uploading the image using html, which as I said I was trying to avoid Oct 12 '16 at 23:40
• You can create a reference to an image element in your script without that tag ever being added to your HTML document. Oct 12 '16 at 23:43
• How? I don't really know much JavaScript. Oct 12 '16 at 23:44
• It's literally the first example in the docs here - just skip the "appendChild" step at the end. Oct 12 '16 at 23:45

Philip's suggested improvement to DMGregory's answer is important.

//Create Image object
var image2 = new Image();

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);
}

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);

• You should do the 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. Oct 18 '16 at 18:00