0

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

Demandooda
  • 122
  • 1
  • 14
  • 1
    What does "not working" mean? Are you not seeing anything? Are some things showing up and others not? Also, you have not included the relevant HTML as that is a potential part of the problem. – Becuzz Dec 08 '15 at 20:30
  • Ill change it so that it is more clear. Thanks. – Demandooda Dec 08 '15 at 20:30
  • Possible duplicate of [CanvasContext2D drawImage() issue \[onload and CORS\]](http://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido Dec 09 '15 at 02:13

1 Answers1

1

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";

}
Anthony Blackshaw
  • 2,549
  • 2
  • 16
  • 20