Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - How to know when browser finish to process an image after loading it?

When an image object is created, can know when is fully loaded using the "complete" property, or the "onload" method, then, this image has processed ( resizing for example ) using some time, that can be some seconds in big files.
How to know when browser finish to process an image after loading it?

EDIT: In examples can see a lag between "complete" message and the appearance of the image, I want avoid this.

Example ussing "onload" method:

var BIGimage;
putBIGimage();
function putBIGimage(){
BIGimage=document.createElement("IMG");
BIGimage.height=200;
BIGimage.src="http://orig09.deviantart.net/5e53/f/2013/347/f/d/i_don_t_want_to_ever_leave_the_lake_district_by_martinkantauskas-d6xrdch.jpg";
BIGimage.onload=function(){waitBIGimage();};
}
function waitBIGimage(){
console.log("Complete.");
document.body.appendChild(BIGimage);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one way.

CanvasContext2D drawImage method is synchronous. Before being able to use this method, the browser has to completely render the image.

So you can use it as a waiting method in your waitBIGimage method.

var BIGimage;
putBIGimage();

function putBIGimage() {
  BIGimage = document.createElement("IMG");
  BIGimage.height = 200;
  BIGimage.src = "https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg?r=" + Math.random();
  BIGimage.onload = waitBIGimage;
  BIGimage.onerror = console.error;
}

function waitBIGimage() {
  // only for demo
  // we've got to also log the time since even the console.log method will be blocked during processing
  var start = performance.now();
  console.log('waiting', start);

  // this is all needed
  var ctx = document.createElement('canvas').getContext('2d');
  ctx.drawImage(this, 0, 0);

  // demo only
  var end = performance.now();
  console.log("Complete.", end);
  console.log(`it took ${end - start}ms`)

  // do your stuff
  document.body.appendChild(BIGimage);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...