0

I already create my canvas on my page, however when I try to import an image on the canvas, it does not appear, here are the code I used. (the makeGameArea is a method I used to create a canvas)

var myGameArea = makeGameArea(700, 600, "myArea", "white");
var myContext = myGameArea.getContext("2d");

var myImage = new Image();
myImage.src = "sonic.gif";
myContext.drawImage(myImage, 100, 100, 100, 100);

Is there any syntax error in my code?

siyi li
  • 49
  • 6
  • Running the code (replacing `makeGameArea` with actual canvas) works fine. I would surmise that the error is either with `makeGameArea` or the image doesn't exist. – Cjmarkham May 21 '17 at 20:10
  • @CarlMarkham I'd assume it is the async loading of the image - the drawing needs to happen in the `myImage.onload` event handler. – le_m May 21 '17 at 20:17
  • Possible duplicate of [Javascript draw dynamic image from URL onto canvas element](http://stackoverflow.com/questions/10282824/javascript-draw-dynamic-image-from-url-onto-canvas-element) – le_m May 21 '17 at 20:18
  • @siyili Just write `myImage.onload = function() { myContext.drawImage(myImage, 100, 100, 100, 100); };` – le_m May 21 '17 at 20:20

1 Answers1

0

I am assuming you already have a canvas element on the page and that it has the id myArea.

Your first line of javascript just does not make sense - unless you have a function called makeGameArea() which you haven't told us about, you cannot create a canvas in that in way.

Secondly you must load the image before you can draw it on the canvas.

Try this code out:

var myGameArea = document.getElementById("myArea"); 
var myContext = myGameArea.getContext("2d");

myGameArea.width = 700;
myGameArea.height = 600;

var myImage = new Image();

myImage.onload = function() {

    myContext.drawImage(myImage, 100, 100, 100, 100);

}

myImage.src = "sonic.gif";
Tom_B
  • 307
  • 2
  • 8
  • Yeah, makeGameArea() is a method I created to make a canvas, since it is so long so I would not want to put here. But anyways, your answer already solve my problemm thanks (I believe it should be myImage.onload instead of zoomImage.onload) – siyi li May 21 '17 at 20:35
  • ah yes sorry, I have a function for loading images that I copied and i missed that. Answer updated. Please accept it if it has answered your question – Tom_B May 21 '17 at 20:38
  • Btw, why I have to load the image before running the script? doesnt the script will automatic load the image for me? – siyi li May 21 '17 at 20:53
  • You need to use the onload function as without it your script will process drawImage before the image has been downloaded i.e. the script does not wait for the image to download before continuing to the next line of code – Tom_B May 21 '17 at 20:58