Fabric.js Ruler With Zoom
Solution 1:
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);
}}
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;
});
Post a Comment for "Fabric.js Ruler With Zoom"