Search code examples
javascripthtml5-canvasscrollbarzoomingpaperjs

Creating scrollbars in an HTML PaperJS canvas element for use with paper.view.zoom


  • We have a PaperJS canvas that is set to 100% width/height
  • Users can zoom and pan
  • Users can add content to the canvas at various places within the canvas regardless of zoom/pan state
  • We want to add scrollbars to the canvas like those used in Figma when there is content outside the currently viewable area

When a user zooms in/out or pans with a PaperJS canvas, they're not moving the actual canvas in the DOM or increasing the canvas element's size. Instead, they're changing the viewing relationship to content within the canvas element.

Thus the scrollbars need to be created in the canvas element but there doesn't appear to be a way to lock the scrollbars ratio. For example, if the scrollbars are in the canvas context and you zoom in, you're zooming on all of the canvas content and the scrollbars change in size as well. It seems like the only solution would be to have some sort of listener in place that always sets their size, position, etc in relation to the zoom/pan state of the canvas, which seems like a lot of extra code. Has anyone come across a solution for this?


Solution

  • You would have to do what you commented on the end of your question.

    • Set initial height of scroll bar to const scrollHeight = view.height
    • Create an update function and attach it to view.onFrame
    • In update function update scroll objects height depending on current zoom scrollObject.bounds.height = scrollHeight / view.zoom
    • You can then determine the scroll bars handle position by getting the position of the highest objects obj.bounds.top, the lowest objects bottom bounds obj.bounds.bottom, and finally use the current view position center to calculate the handle position view.bounds.center