Question

I am trying to create a grid that gets redrawn on each zoom/pan level so that it covers only the currently-viewable-screen area.

How the grids and scroll-zoom-to-mouse-position work:

  • Each zoomIn or zoomOut draws a grid based on the currently-viewable area (using paper.view.bounds as argument for where to start drawing the grid and how many cells are needed)

  • I also delete any previously placed grid on each zoomIn/Out before creating a new grid.

It's a concept of dynamic grid which greatly improves performance since having a very large static grid has a huge performance hit. Therefore the grid only covers the currently-viewable screen area.

The issue is that the grids are not relatively positioned between them.

  • The zoom homes-in on the mouse position thus it changes the paper.view.bounds object. Unfortunately the Grid-Drawing function also uses that object to draw the grid, thus the grids are not positioned relative to each other.

  • If I draw a rectangle on zoom level 1 and then I zoom in/out the rectangle is no longer aligned to the grid, since the grid was placed at a relatively wrong position with the previous grid.

Any ideas?

Was it helpful?

Solution

Although Alex's answer might be more correct,

I have figured out this solution where I create the grid at an xPos/yPos that will definitely correspond to a gridLine placement.

So yPos/xPos have now a correctedBoundingRectLeft and a correctedBoundingRectTop to draw their calculations from

The code:

var drawGrid = function(boundingRect, cellSize) {
  var vCellsNum = boundingRect.height / cellSize;
  var hCellsNum = boundingRect.width / cellSize;

  for (var i = 0; i <= hCellsNum; i++) {
    var offsetXPos = Math.ceil(boundingRect.left / cellSize) * cellSize;
    var xPos = offsetXPos + i * cellSize;
    var topPoint = new paper.Point(xPos, boundingRect.top);
    var bottomPoint = new paper.Point(xPos, boundingRect.bottom);
    var line = new paper.Path.Line(topPoint, bottomPoint);

    line.strokeColor = '#968d8d';
  }

  for (var i = 0; i <= vCellsNum; i++) {
    var offsetYPos = Math.ceil(boundingRect.top / cellSize) * cellSize;
    var yPos = offsetYPos + i * cellSize;
    var leftPoint = new paper.Point(boundingRect.left, yPos);
    var rightPoint = new paper.Point(boundingRect.right, yPos);
    var line = new paper.Path.Line(leftPoint, rightPoint);

    line.strokeColor = '#968d8d';
  }
}

// where `30` is the cell width/height in px
drawGrid(paper.view.bounds, 30);

And a Paper Sketch for the above

OTHER TIPS

It looks like your drawGrid() function will always begin from point (0,0). Instead, you should pass a point as an argument that offsets the grid by the appropriate amount.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top