0
\$\begingroup\$

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

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';
\$\endgroup\$
1
\$\begingroup\$

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);
\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Philipp Oct 18 '16 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.