我目前正在运行我的项目,并且我使用了fabric js来处理canvas。因为我希望我的画布对象不要超出画布边界。我做了this code并且它正常工作,除非并且直到我旋转它。但是当我旋转对象时,该对象的左上角按照旋转进行,我的代码运行不正常。我想要一些解决方案,它可以在任何条件下工作,但我的对象不应该超出画布边界。 感谢
var canvas=new fabric.Canvas('demo');
canvas.on('object:moving',function(e){
if(e.target.getWidth()+e.target.left>canvas.width)
{
e.target.set('left',canvas.width-e.target.getWidth());
e.target.setCoords();
canvas.renderAll();
}
if(e.target.getHeight()+e.target.top>canvas.height)
{
e.target.set('top',canvas.height-e.target.getHeight());
e.target.setCoords();
canvas.renderAll();
}
if(e.target.top<0)
{
e.target.set('top',0);
e.target.setCoords();
canvas.renderAll();
}
if(e.target.left<0)
{
e.target.set('left',0);
e.target.setCoords();
canvas.renderAll();
}
});
var text=new fabric.IText('Jayesh');
canvas.add(text);
<script src="http://fabricjs.com/lib/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<canvas id="demo" style="width:100px;height:100px;border: 1px solid black"></canvas>
答案 0 :(得分:2)
请试一试。
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);