Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom in and out with Fabric JS

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 enter image description here

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?

like image 589
Luigi Caradonna Avatar asked Jan 26 '16 16:01

Luigi Caradonna


2 Answers

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());
like image 164
AndreaBogazzi Avatar answered Sep 19 '22 06:09

AndreaBogazzi


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.

like image 35
nexttus Avatar answered Sep 22 '22 06:09

nexttus