我正在使用fabricjs并试图限制移动/调整图像外的矩形。
这是我到目前为止的小提琴:Fiddle
代码:
var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
canvas.setBackgroundImage('http://www.beatnyama.com/wp-content/uploads/2015/05/assets.jpg', canvas.renderAll.bind(canvas));
this.__canvases.push(canvas);
canvas.observe("object:moving", function(e){
var obj = e.target;
//code goes here to restrict moving/resizing outside image
});
我该如何实现?
答案 0 :(得分:4)
请在此处查看更新的小提琴或运行代码段。 http://jsfiddle.net/h2zvj3un/2/
基本上你不应该使用背景,因为你需要知道图像尺寸。 更容易(可读性方面,你可以使用backgroundImage对象获得相同的效果)来使用普通图像,而不是偶数,不可选择。并设置为画布的背面。
在图像加载时保存其边界坐标。
在物体移动计算对象布线框并检查它是否会触摸图像框。 如果触摸它,请使用最新的已知良好值恢复图像的顶部和左侧值。
var canvas = new fabric.Canvas('canvas');
var minX, minY, maxX, maxY;
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
fabric.Image.fromURL('http://www.beatnyama.com/wp-content/uploads/2015/05/assets.jpg', function(img){
img.evented=false;
img.selectable=false;
canvas.add(img);
minX = img.oCoords.tl.x;
maxX = img.oCoords.br.x;
minY = img.oCoords.tl.y;
maxY = img.oCoords.br.y;
canvas.sendToBack(img);
});
function checkmove(e) {
var obj = e.target;
obj.setCoords();
var b = obj.getBoundingRect();
if (!(b.left >= minX && maxX >= b.left + b.width)) {
obj.left = obj.lastLeft;
obj.scaleX= obj.lastScaleX
obj.scaleY= obj.lastScaleY
} else {
obj.lastLeft = obj.left;
obj.lastScaleX = obj.scaleX
}
if (!(maxY >= b.top + b.height && b.top >= minY)) {
obj.top = obj.lastTop;
obj.scaleX= obj.lastScaleX
obj.scaleY= obj.lastScaleY
} else {
obj.lastTop = obj.top;
obj.lastScaleY = obj.scaleY
}
}
function checkscale(e) {
var obj = e.target;
obj.setCoords();
var b = obj.getBoundingRect();
if (!(b.left >= minX && maxX >= b.left + b.width && maxY >= b.top + b.height && b.top >= minY)) {
obj.left = obj.lastLeft;
obj.top = obj.lastTop;
obj.scaleX= obj.lastScaleX
obj.scaleY= obj.lastScaleY
} else {
obj.lastLeft = obj.left;
obj.lastTop = obj.top;
obj.lastScaleX = obj.scaleX
obj.lastScaleY = obj.scaleY
}
}
canvas.observe("object:moving", checkmove);
canvas.observe("object:scaling", checkscale);

<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id='canvas' width="550" height="550" style="border:#000 1px solid;"></canvas>
&#13;