我想使用Fabricjs庫在圖像上繪製圖像和圓形。 我按照下列步驟操作: 1)在畫布上繪製圖像。 2)在畫布上畫圓。 3)使用鼠標滾動放大/縮小圖像。在imagejs中縮放圖像後無法保留圓的位置
問題: 我可以縮放,這對於圖像來說是完美的,但是圓形的位置會發生變化,例如,如果我通過將圖像拖動到圖像上來保持圓形(例如熊貓的眼睛)和放大/那麼圓圈的位置就會從眼睛轉移到另一個地方。
下面的代碼:
HTML:
<h1>After Zooming the shapes positions are changing<h1>
<canvas id="canvas" height=700 width=700></canvas>
的JavaScript:
var canvas = new fabric.Canvas("canvas");
fabric.Image.fromURL('http://www.nairaland.com/attachments/1539614_pow_jpegfbbdd74848f20f626bb76cedb0cdded3', function(oImg) {
oImg.scale(1.0).set({
left: 1,
top: 1,
selectable : false
});
canvas.add(oImg).setActiveObject(oImg);
var circle = new fabric.Circle({
left: 100,
top: 80,
originX: 'left',
originY: 'top',
radius: 45,
angle: 0,
fill: '',
stroke:'red',
strokeWidth:3
});
canvas.add(circle);
canvas.renderAll();
_applyZoom();
});
var _applyZoom = function() {
canvas.on("mouse:move", function(event) {
currentMouseY = Math.round(event.e.clientY);
});
canvas.getObjects()[0].on("mousemove", function(event) {
currentMouseX = Math.round(event.e.clientX);
});
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel"
if (document.attachEvent)
document.attachEvent("on"+mousewheelevt, _zoom)
else if (document.addEventListener)
document.addEventListener(mousewheelevt, _zoom, false)
return this;
}
function _zoom(e, dragDelta) {
var evt=window.event || e;
var delta = (dragDelta == undefined) ? evt.detail? evt.detail*(-120) : evt.wheelDelta : dragDelta;
var factor = 0.9;
if (delta > 0) {
factor = 1/factor;
}
var objects = canvas.getObjects();
var image = objects[0];
var imageX = (currentMouseX - image.getLeft()),
imageY = (currentMouseY - image.getTop());
var dx = imageX * (factor - 1),
dy = imageY * (factor - 1);
//applying zoom values.
for (var i in objects) {
objects[i].left = objects[i].left - dx;
objects[i].top = objects[i].top - dy;
objects[i].scaleX = objects[i].scaleX * factor;
objects[i].scaleY = objects[i].scaleY * factor;
objects[i].setCoords();
}
canvas.renderAll();
e.preventDefault();
return false;
}
我已經添加了來自Fiddler的代碼。 –
非常感謝@KarlGjertsen – subhfyu546754