I'm implementing the Zoom functionality on canvas with fabric.js. I achieved zooming but somehow its not zooming to centre of canvas. Its zooming to top-left corner of canvas.
Below is my JS for the same.
<script>
var canvas = new fabric.Canvas("Canvas-Id", {
selection: true,
width: 800,
height: 400
});
canvas.setBackgroundImage('http://i24.photobucket.com/albums/c22/smeagolsfree/TSCHQ.png', canvas.renderAll.bind(canvas), {
width: canvas.width,
height: canvas.height
});
initializeCanvas(canvas)
</script>
In my JS file:
var initializeCanvas;
initializeCanvas = function(canvas) {
var MAX_ZOOM_IN, MAX_ZOOM_OUT, SCROLL_SIZE, ZOOM_PERCENT, zoomIn, zoomOut;
SCROLL_SIZE = 120;
ZOOM_PERCENT = 1.2;
MAX_ZOOM_IN = 5;
MAX_ZOOM_OUT = 1;
zoomIn = function() {
if(canvas.getZoom() < MAX_ZOOM_IN) {
canvas.setZoom(canvas.getZoom() * ZOOM_PERCENT);
$('.flaticon-zoom-in').removeClass('disable');
} else {
$('.flaticon-zoom-in').addClass('disable');
}
$('.flaticon-zoom-out').removeClass('disable');
};
zoomOut = function() {
if(canvas.getZoom() > MAX_ZOOM_OUT) {
canvas.setZoom(canvas.getZoom() / ZOOM_PERCENT);
$('.flaticon-zoom-out').removeClass('disable');
} else {
$('.flaticon-zoom-out').addClass('disable');
}
$('.flaticon-zoom-in').removeClass('disable');
};
$('#zoomIn').click(function() {
zoomIn();
});
$('#zoomOut').click(function() {
zoomOut();
});
$('.taggable-image-canvas-container').bind('mousewheel', function(e) {
e.preventDefault();
(e.originalEvent.wheelDelta / SCROLL_SIZE > 0) ? zoomIn() : zoomOut()
});
};
Can anyone suggest me how to achieve zooming to centre of canvas.
It is the expected behavior of setZoom function which is calling zoomToPoint with the top left point as an argument:
setZoom: function (value) {
this.zoomToPoint(new fabric.Point(0, 0), value);
return this;
}
So, zooming on center of the canvas can be achieved by calling zoomToPoint
:
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / ZOOM_PERCENT);
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