Efe Öztürk
Efe Öztürk

Reputation: 33

Fabric.js ruler with zoom

I' ve question. I'm coding an editor like this, and I also want a ruler to add it (which change values with mouse-scroll (zoom in and out) )

But I can't do it. I tried all rulers on github but they are running only body tag.

Unfortunately, there are no documents for zoom in or zoom out.

I'm new with HTML5 canvas and I'm stuck. Waiting for your helps. Thanks!

Upvotes: 3

Views: 4226

Answers (1)

John M
John M

Reputation: 2600

One approach would be to have three separate canvases, one as the main canvas and one each for the top/left rulers.

When zooming in/out, you set the zoom level on the main canvas, but you will need to redraw the rulers manually, here is a really simple example:

function redrawRulers() {
  topRuler.clear();
  leftRuler.clear();
  topRuler.setBackgroundColor('#aaa');
  leftRuler.setBackgroundColor('#aaa');

  zoomLevel = mainCanvas.getZoom();

  for (i = 0; i < 600; i += (10 * zoomLevel)) {
    var topLine = new fabric.Line([i, 25, i, 50], {
      stroke: 'black',
      strokeWidth: 1
    });
    topRuler.add(topLine);
    var leftLine = new fabric.Line([25, i, 50, i], {
      stroke: 'black',
      strokeWidth: 1
    });
    leftRuler.add(leftLine);
  }}

Fiddle

UPDATE: For the rulers, here's some very simple code to draw figures on the top ruler (fiddle also updated):

  // Numbers
for (i = 0; i < 600;  i += (100 * zoomLevel)) {
  var text = new fabric.Text((Math.round(i / zoomLevel)).toString(), {
    left: i,
    top: 10,
    fontSize: 8
  });
  topRuler.add(text);
}

Now, of course you will want to convert those numbers into whatever units are appropriate for your application. Also, you may want to consider drawing the numbers at more frequent intervals when you're zoomed in, and to space them out more when you're zoomed out. But I think I've given you enough to get you going here.

Add the below code in document.ready this will bind a mouse scroll event with the canvas and hence the zoom in and out will happen when you use mousewheel.

$(mainCanvas.wrapperEl).on('mousewheel', function(e) {
    var dir = e.originalEvent.wheelDelta;
    if (dir > 0){
      var ZoomValue = mainCanvas.getZoom() * 1.2;           

    } else {
        var ZoomValue = mainCanvas.getZoom() * .83333333333333333;
    }

    redrawRulers();
    mainCanvas.setZoom(ZoomValue, e);
    e.originalEvent.returnValue = false;
});

Updated Fiddle For Mouse Scroll

Upvotes: 5

Related Questions