我正在使用fabric.js在画布上实现缩放功能。我实现了缩放,但不知何故它没有缩放到画布中心。它缩放到画布的左上角。
以下是我的JS。
<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>
在我的JS文件中:
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()
});
};
任何人都可以建议我如何缩放到画布中心。
答案 0 :(得分:9)
setZoom函数的预期行为是以左上角为参数调用zoomToPoint:
setZoom: function (value) {
this.zoomToPoint(new fabric.Point(0, 0), value);
return this;
}
因此,可以通过调用zoomToPoint
:
canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), canvas.getZoom() / ZOOM_PERCENT);