0

I have this very simple code to load an image on a canvas. Can you tell my why I have to click twice the button to have the image loaded? (I'm using chrome)

<!DOCTYPE html>
<html>
    <body>
        <canvas id="c" width="200" height="200"></canvas>
        <script type="text/javascript" src="T4_referencing.js"></script>
        <input id="b" type="button" onclick="display()"></input>
    </body>
</html>

T4_referencing.js

function display(){
    var canvas=document.getElementById("c");
    var ctx=canvas.getContext("2d");

    var im = new Image;
    im.src="T3default200x200.png";

    ctx.drawImage(im,0,0);
}

Thanks!

Katerl3s
  • 263
  • 1
  • 10
  • Do you reproduce your issue with this [fiddle](http://jsfiddle.net/3tqe3ay8/) ? – Amessihel Oct 06 '15 at 09:53
  • @KeyDamo: That makes it a duplicate. – Madara's Ghost Oct 06 '15 at 12:27
  • @MadaraUchiha I DON'T disagree with you. I had a look at http://stackoverflow.com/help/duplicates and the blog post therein: "it's OK for duplicate questions to have duplicate answers" and " we love (some) dupes". That's because dupes help finding the answer. "people tend to ask and search using completely different words, and the better our coverage, the better odds people can find the answer they’re looking for". – Katerl3s Oct 06 '15 at 14:30

1 Answers1

1

You need to to call drawImage after the image has loaded fully:

im.onload=function() {
    ctx.drawImage(im, 0, 0);
}

The reason it worked on the second click is that the image has then been loaded (requested by the first click) and is taken straight from memory without the network delay.

andrrs
  • 2,289
  • 3
  • 17
  • 25