Search code examples
javascriptcanvaspaperjs

how to scroll canvas with paperjs?


I have not been able to scroll through canvas move whole paper horizontally and vertically.

It is possible?

<script type="text/javascript" src="~/Scripts/PaperJS/paper-full.js"></script>

<script type="text/javascript" src="~/Scripts/PaperJS/paper-core.js"></script>

<script>
  $(document).ready(function () {
      var canvas = document.getElementById('odbCanvas');
      paper.setup(canvas);
      var path = new paper.Path();
      path.strokeColor = 'white';
      var start = new paper.Point(100, 100);
      path.moveTo(start);

      path.lineTo(start.add(0,40));
      path.lineTo(start.add(40,40));
      path.lineTo(start.add(40,0));
      path.lineTo(start.add(0,0));

      paper.view.draw();

      path.on('mousedrag', function (event) {
          this.position = event.point;
      });
  });
</script>

Solution

  • You can use paper.view.scrollBy(new Point(x, y)) to scroll the whole View

    Here's some example code:

    // Draw a Rectangle for reference
    var rect = new Path.Rectangle(new Point(200, 100), new Point(50, 50))
    rect.strokeColor = 'black'
    rect.strokeWidth = 1
    
    // Create a Tool so we can listen for events
    var toolPan = new paper.Tool()
    toolPan.activate()
    
    // On drag, scroll the View by the difference between mousedown 
    // and mouseup
    toolPan.onMouseDrag = function (event) {
      var delta = event.downPoint.subtract(event.point)
      paper.view.scrollBy(delta)
    }
    

    And here's a Sketch for this (drag your mouse on the canvas)


    Side note: You don't need to include both paper-core.js and paper-full.js. Use one or the other, depending whether you need PaperScript support as well (paper-full.js includes PS as well).