0

i have an image in an HTML tag


<img id="enemy" src="img/enemy.png" style="display: none;">

which I'm then getting by Id into a variable, like always, and then drawing via


canvasContext.drawImage(enemy, enemyX, enemyY);

I have already set up the canvas and its context('2d') and it works in everything I throw at it, but I cannot draw there the image above. I get the error


TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, SVGImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap.


davide m.
  • 452
  • 4
  • 19
  • https://stackoverflow.com/questions/28478564/error-when-drawing-canvas-picture-from-base-64-string You can see the answer here. –  Oct 13 '18 at 20:06
  • 1
    Can we see the code by which you're "getting by Id into a variable?" – Luke Taylor Oct 13 '18 at 20:07

2 Answers2

2

This should work :

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("enemy");
ctx.drawImage(img, 10, 10);

myCanvas in your canvas. maybe you do not get your image element in javascript.

Obtice
  • 1,205
  • 3
  • 18
  • 44
  • I do get it, and it draws everything else without any problem. as you see above, canvasContext calls the function drawImage as you suggested but I still get that error – davide m. Oct 14 '18 at 09:39
0

Found the answer myself, it's pretty confusing because I have found out that the problem persists in all the browsers and only works if getElementById is stated just after canvasContext, but I can accept it. Otherwise the image on JavaScript should be constructed as


var img = new Image();
img.src = "folder/image.png";

without having to append the image onto HTML.

davide m.
  • 452
  • 4
  • 19