![](/img/trans.png)
[英]How to make an object on canvas moving left and right to the x-axis smoothly on mobile devices
[英]How to prevent canvas object movement X-axis left direction only (FabricJS)
我正在嘗試將畫布對象綁定到織物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;
選項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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.