Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an image has finished rendering in the browser (i.e. painted)?

On a web app I need to work with a lot of high-res images, which are dynamically added to the DOM tree. They are pre-loaded, then added to the page.

It's one thing to detect when such an image has finished loading, for this I use the load event, but how can I detect when it has finished being rendered within the browser, using Javascript? When working with high resolution images, the actual painting process can take a lot of time and it's very important to know when it ends.

like image 285
Andrei Oniga Avatar asked Jan 29 '13 08:01

Andrei Oniga


People also ask

How are browser images rendered?

A simple text and image are rendered on the screen. From previous explanations, the browser reads raw bytes of the HTML file from the disk (or network) and transforms that into characters. The characters are further parsed into tokens.

What is render in image?

Rendering or image synthesis is the process of generating a photorealistic or non-photorealistic image from a 2D or 3D model by means of a computer program. The resulting image is referred to as the render.


2 Answers

I used requestAnimationFrame to do the trick. After image loaded it will be rendered during the next animation frame. So if you wait two animation frames your image will be rendered.

function rendered() {     //Render complete     alert("image rendered"); }  function startRender() {     //Rendering start     requestAnimationFrame(rendered); }  function loaded()  {     requestAnimationFrame(startRender); } 

See http://jsfiddle.net/4fg3K/1/

like image 157
hovitya Avatar answered Oct 08 '22 22:10

hovitya


I had the same problem. I have created the preloader page with progress bar. When the image is loaded, the white background preloader page disappears smoothly to opacity: 0, but the image is still not rendered.

I have finally used the setInterval, when the image is loaded (but not rendered). In the interval I check the naturalWidth and naturalHeight properties (Support: IE9+). Initialy it equals 0 and when the image is rendered it shows its current width and height.

const image = document.getElementById('image');    image.src = "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-1.jpg";    image.onload = function () {    console.log('Loaded: ', Date.now());    const interval = setInterval(() => {      if (image.naturalWidth > 0 && image.naturalHeight > 0) {        clearInterval(interval);        rendered();      }    }, 20);  }    function rendered() {    console.log('Rendered: ', Date.now());  }
img{    width: 400px;  }
<img id="image"/>
like image 44
Paweł Avatar answered Oct 08 '22 21:10

Paweł