简体   繁体   中英

Javascript - canvas - drawImage does not work

I have read all the other similar posts but I don't understand why it I have this problem.

I have a canvas (#canvas) and an image (hero.png) on the page, and a JS file loaded at the end of the body. In the JS code...

This works:

var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.draw = function(){
  game.ctx.drawImage(game.hero, 200, 200);
}
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;

And this doesn't work:

var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;
game.draw = function(){
  game.ctx.drawImage(game.hero, 200, 200);
}

Nothing appears. No error in the console. Why???

Thanks!

You can call functions before define them only with this syntax:

function draw() 
{
  //COde here
}

By writting

game.draw = function(){};

You define a method to your object, you don't define a JavaScript function: that's why you can't call it before define it :)

In your second hunk of code, you're defining

game.hero.onload = game.draw;

When game.draw is undefined, so your onload is undefined and nothing happens when the image is done loading.

game.draw is not set when you assign it in your second example, you are copying an undefined value into hero.onload .

One workaround is to wrap the function you want to call in an anonymous function and call yours from there:

game.hero.onload = function(){ game.draw(); };

Have in mind that if hero loads before the definition of game.draw is finished, this code will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM