2

I'm working on a web development lab, but my image is not showing up. Is there something I am doing wrong in referencing the image? Here is a link to the image itself: http://tuftsdev.github.com/WebProgramming/assignments/pacman10-hp-sprite.png

Note: I copied the image into my local directory, so I know the the referencing is correct.

 <!DOCTYPE html>
 <html>
 <head>
     <title>Ms. Pacman</title>
     <script>
         function draw() {
             canvas = document.getElementById('simple');

             // Check if canvas is supported on browser
             if (canvas.getContext) {
                ctx = canvas.getContext('2d');
                var img = new Image();
                img.src = '"pacman10-hp-sprite.png';
                ctx.drawImage(img, 10, 10);
             }
             else {
                alert('Sorry, canvas is not supported on your browser!');
             }
       }
     </script>
  </head>

 <body onload="draw();">
     <canvas id="simple" width="800" height="800"></canvas>
 </body>
 </html>

1 Answer 1

2

You'll need to set up a callback and draw the image to the canvas once the image has actually loaded:

function draw() {
    canvas = document.getElementById('simple');

    // Check if canvas is supported on browser
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        var img = new Image();

        // If you don't set this callback before you assign
        // the img.src, the call ctx.drawImage will have 
        // a null img element. That's why it was failing before
        img.onload = function(){
            ctx.drawImage(this, 10, 10);
        };

        img.src = "pacman10-hp-sprite.png";
    } else {
        alert('Sorry, canvas is not supported on your browser!');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.