Reputation: 17
I've played around with the draw function but now that i'm moving on to images i've hit a brick wall. here is the code:
var x
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();
ghost.src = "ghost.png"
window.setTimeout(x, 5000);
var drawIm = function (sprite) {
ctx.save();
ctx.translate(100, 100);
ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
ctx.restore();
};
drawIm(ghost);
I'm sure it's nothing to do with the file names or anything, and i can't see any problem with it, but the ghost just won't appear! What's the problem?
Upvotes: 0
Views: 63
Reputation: 32859
You need to draw the ghost when it's loaded. SO, do something like ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();
//ghost onload event
ghost.onload = function() {
drawIm(ghost);
}
ghost.src = "https://lessonpix.com/drawings/2587/100x100/Happy+Ghost.png";
var drawIm = function(sprite) {
ctx.save();
ctx.translate(100, 100);
ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
ctx.restore();
};
<canvas id="canvas" width="200" height="200"></canvas>
Upvotes: 1