Skip to content

Commit

Permalink
Merge pull request #151 from EugenDueck/feature/progressive-rendering
Browse files Browse the repository at this point in the history
Support progressive rendering in PanZoomWithCover
  • Loading branch information
sasza2 authored Apr 4, 2024
2 parents de534c1 + fe0576d commit be35950
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/PanZoomWithCover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ const PanZoomWithCover: React.FC<

const image = new Image();
image.src = cover;
image.onload = () => {
let imageAttached = false;
const attachImageToDom = () => {
// attachImageToDom may get called multiple times, but we want to attach only once
if (imageAttached) return;
imageAttached = true;

const containerNode = parentRef.current.parentNode as HTMLElement;
const containerSize = containerNode.getBoundingClientRect();

Expand Down Expand Up @@ -71,7 +76,27 @@ const PanZoomWithCover: React.FC<
if (onCoverLoad) onCoverLoad();
};

const imageLoadIntervalId = setInterval(() => {
if (image.naturalWidth > 0 && image.naturalHeight > 0) {
// naturalWidth and naturalHeight are all we need for scale calculations, so we can start
// progressively rendering the image
attachImageToDom();
clearInterval(imageLoadIntervalId);
}
}, 100);

// In case if image gets loaded sooner (for e.g. from cache)
const onImageLoad = () => {
attachImageToDom();
clearInterval(imageLoadIntervalId);
};

image.addEventListener('load', onImageLoad);

return () => {
clearInterval(imageLoadIntervalId);
image.removeEventListener('load', onImageLoad);

if (!panZoomRef.current) return;
panZoomRef.current.destroy();
panZoomRef.current = null;
Expand Down

0 comments on commit be35950

Please sign in to comment.