I'm building a simple image editor using FabricJS. I can do almost anything I need, the problem comes implementing a zoom feature. As far as I've understood, FabricJS hasn't anything built-it, so that I'm trying to do it by myself.
I've put 2 buttons on the page "Zoom in" and "Zoom out", on click they activate a jQuery function, respectively
$("#zoomin").click(function() {   
    $("#canvas").width(
        $("#canvas").width() * 1.25
    );
    $("#canvas").height(
        $("#canvas").height() * 1.25
    );
});
and
$("#zoomout").click(function() {
    $("#canvas").width(
        $("#canvas").width() * 0.8
    );
    $("#canvas").height(
        $("#canvas").height() * 0.8
    );
});
Where #canvas is the id of the div which contains the canvas. This code works properly, it actually zooms in and out, but that causes a problem when I want to grab and move around the objects on the canvas, the snap area is not where the object is visible, when I zoom in, the snap area results to be moved to top-left of the visible object, when I zoom out it results to be moved to the bottom-right.
To explain, this is what happens after a zoom out

Is there a way to make the snap area consistent with the position of the shown object?
Is there a better way to implement the zooming function?
fabrcjs has its own zooming functions built inside.
I think that in this way you are obtaining a css zoom of the element, but mouse interaction is calculated internally with objects positions.
Try to use fabricjs functions:
canvas.setZoom(val);
Where canvas is the fabric.Canvas object.
To resize the canvas accordingly:
canvas.setWidth(originalWidth * canvas.getZoom());
canvas.setHeight(originalHeight * canvas.getZoom());
You can try code below.
canvas.renderAll();
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" ;
document.addEventListener(mousewheelevt, function(e){
    if(e.detail<0){
        //canvas.setZoom(canvas.getZoom() * 1.1 );
        canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() * 1.1);
    }
    else{
        //canvas.setZoom(canvas.getZoom() / 1.1 );
        canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / 1.1);
    }
}, false);
Hope it will work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With