davide m.
davide m.

Reputation: 462

Could not draw an image onto canvas

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.


Upvotes: 0

Views: 1747

Answers (2)

davide m.
davide m.

Reputation: 462

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.

Upvotes: 0

Obtice
Obtice

Reputation: 1269

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.

Upvotes: 2

Related Questions