I am currently running with my project and in that i have used fabric js to work with canvas. In that i want my canvas object not to go out of canvas boundary.I did this code and it is working fine unless and until i am rotating it. but when i am rotating the object, top left of that object is getting as per rotation and my code is not working well. I want some solution which will work in any condition but my object should not go outside of canvas boundary. Thanks
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>