Get the Visible Annotations on the Current Page

To retrieve the annotations that are currently visible on a page, pass the current visible dimensions and coordinates to instance.transformContentClientToPageSpace() to retrieve the visible page bounding box in page units, which will allow you to compare them to the page annotation’s bounding boxes.

The following snippet shows an example of how to achieve this for the current page (it can be repeated for the previous and next pages if needed):

function getPageVisibleRect(pageIndex) {
  // Page DOM element.
  const pageEl = instance.contentDocument.querySelector(
    `.PSPDFKit-Page[data-page-index="${pageIndex}"]`
  );
  const pageBoundingClientRect = pageEl.getBoundingClientRect();
  // Viewport DOM element.
  const viewportEl = instance.contentDocument.querySelector(
    ".PSPDFKit-Viewport"
  );
  // Toolbar DOM element, which needs offsetting.
  const toolbarEl = instance.contentDocument.querySelector(
    ".PSPDFKit-Toolbar"
  );
  // Get the visible page area in page units.
  return instance.transformContentClientToPageSpace(
    new PSPDFKit.Geometry.Rect({
      left: Math.max(pageBoundingClientRect.left, 0),
      top: Math.max(pageBoundingClientRect.top, toolbarEl.scrollHeight),
      width: Math.min(pageEl.clientWidth, viewportEl.clientWidth),
      height: Math.min(pageEl.clientHeight, viewportEl.clientHeight)
    }),
    pageIndex
  );
}

function detectVisibleAnnotations() {
  const pageIndex = instance.viewState.currentPageIndex;
  const pageRect = getPageVisibleRect(pageIndex);
  // Traverse page annotations and check if their bounding box
  // overlaps the visible area.
  instance.getAnnotations(pageIndex).then((annotations) => {
    annotations.forEach((annotation) => {
      if (annotation.boundingBox.isRectOverlapping(pageRect)) {
        // Visible annotation detected. Log it (or keep a reference to it somewhere).
        console.log(annotation.toJS());
      }
    });
  });
}

// Listen to the `viewState.zoom.change` event, which is triggered on every zoom change.
instance.addEventListener(
  "viewState.zoom.change",
  detectVisibleAnnotations
);
// Listen to the `viewState.currentPageIndex.change` event, which is triggered on every zoom change.
instance.addEventListener(
  "viewState.currentPageIndex.change",
  detectVisibleAnnotations
);
// Detect visible annotations again whenever they change.
instance.addEventListener(
  "annotations.create",
  detectVisibleAnnotations
);
instance.addEventListener(
  "annotations.update",
  detectVisibleAnnotations
);
instance.addEventListener(
  "annotations.delete",
  detectVisibleAnnotations
);

This has been tested with PSPDFKit for Web 2020.2.4.