0

I was making a game using HTML5 canvas. Halfway through making my game, I decided to change my game sprite into a spaceship. But as I soon learned, you need to have an image tag to use the c.drawImage function and I did not want to include an image tag in my HTML because it would ruin the margin and padding around my game and I did not want random image dotted around my game just to use a new sprite.

const canvas = document.getElementById("game")

let c = canvas.getContext("2d")

c.drawImage("https://heckapix.com/images/spaceship-clipart-with-background.jpg", 20, 20)
<canvas id="game"></canvas>

So is there a function to draw images from a link or is there a way to make the function work without making an image tag?

  • Possible duplicate of [Drawing an image from a data URL to a canvas](https://stackoverflow.com/questions/4773966/drawing-an-image-from-a-data-url-to-a-canvas) – R. Schifini Nov 17 '19 at 01:06

2 Answers2

0

You can do it if you pre-load your remotely hosted image in an img tag, and hide it (style attribute):

<img id="my-image" src="https://heckapix.com/images/spaceship-clipart-with-background.jpg" style="display: none; visibility: hidden;">

Then use the DOM img in the context:

let img = document.getElementById('my-image');
c.drawImage(img, 20, 20)
Zlatan Omerović
  • 3,863
  • 4
  • 39
  • 67
0

I'm not sure I fully understand why you're using the image in the HTML (and using CSS to make it invisible), but you can always convert it to a Base64 string, and load it into the canvas using JavaScript:

let img = new Image();
img.src = 'data:image/png;base64, VBORw0KGgoAAAANSUhEUgAAAAUAAAAFCCNbyblAA....==';
c.drawImage(img);
Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159