Thursday, 27 April 2023

Calculating visible area in infinite webpage

I'm using @panzoom/panzoom package for creating infinite webpage where I have items placed on it. When user pans I need to lazyload items based on their x and y coordinates. To achieve lazyload of items I need to calculate visible area on the screen.

Working example: Codesandbox

const lazyload = e => {
    if (!panzoomInstance || !panzoomElem) return false;

    const scale = panzoomInstance.getScale();
    const pan = panzoomInstance.getPan();
    const { width, height } = document
      .getElementById("container")
      .getBoundingClientRect();

    const x1 = (0 - pan.x) / scale;
    const y1 = (0 - pan.y) / scale;
    const x2 = (width - pan.x) / scale;
    const y2 = (height - pan.y) / scale;

    const visibleArea = {
      x1: Math.floor(x1 * scale),
      y1: Math.floor(y1 * scale),
      x2: Math.floor(x2 * scale),
      y2: Math.floor(y2 * scale)
    };

    const itemsToLoad = items.filter(
      i =>
        i.x >= visibleArea.x1 &&
        i.x <= visibleArea.x2 &&
        i.y >= visibleArea.y1 &&
        i.y <= visibleArea.y2
    );

    console.log(`scale ${scale}`);
    console.log(`pan ${JSON.stringify(pan)}`);
    console.log("visibleArea", visibleArea);

    itemsToLoad.map(i => console.log(i.x, i.y));

    console.log(`found ${itemsToLoad.length} \n\n`);
};

Issue: Above calculation for getting visible area works fine when the scale is >= 1. Anything less than one will result in wrong calculation meaning the x and y coords I'm getting does not cover entire visible area.



from Calculating visible area in infinite webpage

No comments:

Post a Comment