简体   繁体   中英

Why does the first load fail, but subsequent loads work?

The question is best demonstrated with a jsFiddle. Here is is.

So according to this code:

var canvas = document.getElementById('canvas');
canvas.width = 200;
canvas.height = 150;
var context = canvas.getContext('2d');
context.rect(20,20,50,50);
context.stroke();
var image = new Image();
image.src = canvas.toDataURL("image/png");
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0);

you should see a rectangle drawn to the canvas every time you load the page. However, for some reason the first page load always shows nothing, a "blank"...

This point can be proven by opening the jsFiddle link in separate Chrome "Incognito" tabs. You won't ever see the rectangle load on the first time. Refreshing however it will appear.

And just to prove that you are indeed supposed to be seeing a rectangle on the initial load, try updating the jsFiddle to this:

var canvas = document.getElementById('canvas');
canvas.width = 200;
canvas.height = 150;
var context = canvas.getContext('2d');
context.rect(20,20,50,50);
context.stroke();
//var image = new Image();
//image.src = canvas.toDataURL("image/png");
//context.clearRect(0, 0, canvas.width, canvas.height);
//context.drawImage(image, 0, 0);

and you will see the rectangle on each first-load.

Why does the first load show nothing?

You have to wait for the image to load before you can dray it, and it works on the reload because it gets cached

image.onload = function(){
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(image, 0, 0);
}

http://jsfiddle.net/hJ9WQ/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM