Reputation: 122
Here is a very straightforward bit of code I made, that just isn't working! It is throwing no errors.
window.onload = function() {
var canvas = document.getElementById("paper");
var bob = canvas.getContext("2d");
var background = canvas.getContext("2d");
background.fillStyle = "rgb(0, 0, 0)"
background.fillRect(0, 0, 400, 400);
var bobImg = new Image();
bobImg.src = "Drawing (1).png";
bob.drawImage(bobImg, 35, 35, 400, 400);
}
It should be working, and I am having a similar prob with other programs I made. It is just showing the black background, but not the image. Thank you guys for any help! =D
Upvotes: 0
Views: 1512
Reputation: 2549
You need to wait for the image to load before you can draw it. To do that add an event handler for the image load event and put your draw code there. For example:
window.onload = function() {
var canvas = document.getElementById("paper");
var bob = canvas.getContext("2d");
var background = canvas.getContext("2d");
background.fillStyle = "rgb(0, 0, 0)"
background.fillRect(0, 0, 400, 400);
var bobImg = new Image();
bobImg.addEventListener("load", function() {
bob.drawImage(bobImg, 35, 35, 400, 400);
}, false);
bobImg.src = "Drawing (1).png";
}
Upvotes: 1