我正在尝试的是在画布画布中绑定画布对象。通常在创建一个obejct时,它可以移动到画布之外,如下所示:
但我想只在画布内移动它。它不能在外面。这是我的代码:
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;
但我认为这不会解决我的问题。
答案 0 :(得分:1)
有很多解决方案:
JS Part:
$(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