fabricjs canvas with background image is not zoomable and panable

17 views Asked by At

I have canvas created with fabricjs. When I add an image to the canvas, I can't zoom and pan on a mobile phone.

I have this code but it's not working:

var canvas = new fabric.Canvas('canvas', {
    // Set interactive mode to allow zooming
    selection: false
});

try {
    var imageElement = document.createElement('img');
    imageElement.src = "https://navigator.beyonity.ch/data/856B0452/f1012/comp_page1.jpg"
        // Add the image to the canvas when needed
    imageElement.onload = function() {
        fabric.Image.fromURL('https://navigator.beyonity.ch/data/856B0452/f1012/comp_page1.jpg', (img) => {
            // fabric.Image.fromURL(imageElement.src, (img) => {
            let canvasBgImage = img;
            canvas.setBackgroundImage(canvasBgImage, canvas.renderAll.bind(canvas));
            canvas.renderAll()
        });
    };
} catch (error) {
    console.log('error', error)
}
canvas.forEachObject(function(obj) {
    obj.selectable = false;
});

var scaleFactor = 1.1; // Zoom scale factor
var zoomDelta = 0.05; // Incremental delta for smooth zooming
var pinchStartScale = 1; // Initial pinch scale
var lastTouchDistance = 0; // Initial touch distance


// Handle pinch gesture to zoom the canvas
canvas.on('touch:gesture', function(event) {
    if (event.e.touches && event.e.touches.length === 2) {
        var touch1 = event.e.touches[0];
        var touch2 = event.e.touches[1];
        var touchDistance = Math.sqrt(Math.pow(touch2.clientX - touch1.clientX, 2) + Math.pow(touch2.clientY - touch1.clientY, 2));

        if (lastTouchDistance !== 0) {
            var delta = touchDistance - lastTouchDistance;
            var zoom = pinchStartScale + delta * zoomDelta;
            var zoomCenter = new fabric.Point((touch1.clientX + touch2.clientX) / 2, (touch1.clientY + touch2.clientY) / 2);

            canvas.zoomToPoint(zoom / canvas.getZoom(), zoomCenter);
        }

        lastTouchDistance = touchDistance;
    } else {
        lastTouchDistance = 0;
    }
});

// Reset last touch distance when gesture ends
canvas.on('touch:gesture:end', function(event) {
    lastTouchDistance = 0;
});

// Disable native touch scroll
canvas.allowTouchScrolling = false;
0

There are 0 answers