我正在尝试使用Fabricjs库在图像上绘制图像和圆圈。 我遵循以下步骤: 1)在画布上绘制图像。 2)在画布上绘制圆圈。 3)使用鼠标滚动来放大/缩小图像。
问题: 我能够进行缩放,这对于图像非常有效,但是圆圈的位置会发生变化,例如,如果我通过在图像上拖动它来保持圆圈(例如Panda的眼睛)和放大/缩小,圆圈的位置从眼睛转移到其他地方。
以下是代码:
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;
}
答案 0 :(得分:1)
主要问题是在for循环中,当您尝试为对象提供新维度时。
我改变了for循环并且没问题
for (var i in objects) {
var scaleX = objects[i].scaleX;
var scaleY = objects[i].scaleY;
var left = objects[i].left;
var top = objects[i].top;
var tempScaleX = scaleX * factor;
var tempScaleY = scaleY * factor;
var tempLeft = left * factor;
var tempTop = top * factor;
objects[i].scaleX = tempScaleX;
objects[i].scaleY = tempScaleY;
objects[i].left = tempLeft;
objects[i].top = tempTop;
objects[i].setCoords();
}
希望有所帮助,祝你好运。