Why do I have to click twice to create an image?

Asked

Viewed 52 times

1

function myCanvas() {
    var c = document.querySelector('#myCanvas');
    var ctx = c.getContext('2d');
    var img = new Image();
    img.src = 'https://www.w3schools.com/html/img_the_scream.jpg';

    ctx.drawImage(img, 10, 10);
}
<canvas id="myCanvas" width="650" height="600" style="border:1px solid black;overflow: scroll;"></canvas>
<br>
<button onclick="myCanvas()">Click</button>

In the code snippet above I need to double-click to create an image within the element <canvas> why is this happening? I want the first click to create an image.

1 answer

1


What happens is that the image takes a while to load, so you’re having the <canvas> before you knew what draw in fact. The second time works because you had already downloaded the image and it was cached.

To solve this, send draw on <canvas> after the load (loading) of the image. There is a similar example in MDN documentation.

function myCanvas() {
    var c = document.querySelector('#myCanvas');
    var ctx = c.getContext('2d');
    var img = new Image();

    img.onload = function () {
        ctx.drawImage(img, 10, 10);	
    };

    img.src = 'https://www.w3schools.com/html/img_the_scream.jpg';
}
<canvas id="myCanvas" width="650" height="600" style="border:1px solid black;overflow: scroll;"></canvas>
<br>
<button onclick="myCanvas()">Click</button>

It is recommended to put the .onload before indicating the .src not to risk the image being downloaded before the .onload be assigned, because if this happened, the .onload would never be executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.