I have implemented a zoom feature in my canvas. I am using fabricjs for canvas. In my case, a background image is set on canvas. Now when I zoom in and zoom out, the whole canvas gets zoom in and out without any crop and also the select object inside image does not change its position as well. Everything is working fine but the problem is it zooms in and out from top left instead. However, I want zoom in and out from the center not top left corner. I have used canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), zoom); but this did not work for me. I have to use setZoom() otherwise image gets cropped.
The rectangle box that is drawn on the image also moves if setZoom is not used and if it is used I cannot zoom in and out from the center
this is the code
handleZoomOnMouseEvent(e, canvas) {
let zoom = canvas.getZoom();
zoom = parseFloat(zoom, 100)
if (e.ctrlKey) {
e.preventDefault()
e.stopPropagation()
let min = 0
const delta = e.deltaY;
if (delta > 0) {
zoom -= 0.01;
if (this.min_zoom > 0.05) min = 0.05
else min = this.min_zoom
if (zoom <= min) zoom = min;
}
else {
zoom += 0.01;
if (zoom >= 1.5) zoom = 1.5;
}
handleZoom(zoom)
}
},
handleZoom(zoom, e){
// var stroke = this.strokeWidth
canvas.setDimensions({
width: canvas.backgroundImage.width * canvas.getZoom(),
height: canvas.backgroundImage.height * canvas.getZoom()
});
canvas.backgroundImage.rotate(0);
canvas.viewportCenterObject(canvas.backgroundImage);
canvas.renderAll();
canvas.setZoom(zoom);
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), zoom);
// if (e !== undefined) {
// const pointer = canvas.getPointer(e)
// const posx = pointer.x
// const posy = pointer.y
// canvas.zoomToPoint(new fabric.Point(posx, posy), Math.min(Math.max(zoom + (e.deltaY/150), .5), .6));
// } else {
// canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), zoom);
// }
canvas.setDimensions({
width: canvas.backgroundImage.width * canvas.getZoom(),
height: canvas.backgroundImage.height * canvas.getZoom()
});
canvas.renderAll();
},