我正在尝试将 Canvas 对象绑定(bind)在织物 Canvas 中。通常,当创建对象时,可以将其移动到 Canvas 外部,如下所示:
但我只想将其移动到 Canvas 内部。它不能移动到外部。这是我的代码:
var canvas = new fabric.Canvas('c');
var SampleText = new fabric.Text(Text, {
left: canvas.getWidth() / 2,
top: canvas.getHeight() / 2
});
SampleText.on('moving', function(e) {
// need to immplement the logic here
});
canvas.add(SampleText);
canvas.renderAll();
我已经看到了选项 canvas.item(0).lockMovementX = true;
但我认为它不能解决我的问题。
最佳答案
对此有很多解决方案:
JS 部分:
$(document).ready(function() {
var canvas=new fabric.Canvas('demo');
canvas.on('object:moving', function (e) {
var obj = e.target;
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
return;
}
obj.setCoords();
// top-left corner
if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
}
// bot-right corner
if(obj.getBoundingRect().top+obj.getBoundingRect().height > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
}
});
var text=new fabric.IText('Jayesh');
canvas.add(text);
});
看看这个 JsFiddle
关于javascript - 如何防止 Canvas 对象仅在X轴向左方向移动(FabricJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067662/