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.


2

2 Answers 2

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.

1
  • 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, 2018 at 9: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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