Search code examples
javascripttouchfabricjs

Change pinch-zoom sensitivity in fabric.js


I have a custom built fabric.js bundle with touch support. Now I can scale any object with the pinch-zoom gesture. The problem is the zoom is really really sensitive, I barely move my fingers and the object is hugely scaled.

I couldn't find much information in the documents about how I can change the sensitivity. I know Event.js is used to handle the touch events within fabric.js. Is there any way I can change this sensitivity?


Solution

  • Ok, I ended up implementing touch controls myself, this is the code I made. This code was placed on the added event of my custom fabric.js object.

    ////////////////////////////// Touch event handlers
    // Add listener event for pinch-zoom
    var bbScope = this;
    var hammer = new Hammer.Manager(this.canvas.upperCanvasEl);
    var pinch = new Hammer.Pinch();
    hammer.add([pinch]);
    
    hammer.on('pinch', function (ev) {
        // Set the scale and render only if we have a valid pinch (inside the object)
        if (bbScope._validPinch) {
            bbScope.set('scaleX', ev.scale);
            bbScope.set('scaleY', ev.scale);
            bbScope.canvas.renderAll();
        }
    });
    hammer.on('pinchend', function (ev) {
        bbScope._validPinch = false;
    });
    hammer.on('pinchcancel', function (ev) {
        bbScope._validPinch = false;
    });
    hammer.on('pinchstart', function (ev) {
        // Convert mouse coordinates to canvas coordinates
        ev.clientX = ev.center.x;
        ev.clientY = ev.center.y;
    
        // Check if the pinch was started inside this object
        if (bbScope.canvas) {
            var p = bbScope.canvas.getPointer(ev);
            bbScope._validPinch = bbScope.containsPoint(p);
        }
        else {
            bbScope._validPinch = false;
        }
    });