user3356048 - 1 year ago 168
Javascript Question

# fabric.js limit rotation to x degrees with rotation handle

I am using fabric.js and trying to allow rotation for any object on my canvas, not freely 360 degrees, but only 15 degrees at a time, using the rotation handle. I searched really hard but couldn't find an answer so far. Is this possible?

You can use `canvas.on("object:rotating")` to interfer with rotation of all objects. I defined a set of valid angles, and then on the rotation event i checked which one to use.

``````var angles = [0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345, 360];

canvas.on("object:rotating", function(rotEvtData) {
var targetObj = rotEvtData.target;
var angle = targetObj.angle % 360;
for (var i=0; i < angles.length; i++) {
if (angle <=  angles[i]) {
targetObj.angle = angles[i];
break;
}
}
});
``````

``````var canvas = new fabric.Canvas("c");

var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 90,
height: 90
});

var angles = [0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345, 360];
canvas.on("object:rotating", function(rotEvtData) {
var targetObj = rotEvtData.target;
var angle = targetObj.angle % 360;
for (var i=0; i < angles.length; i++) {
if (angle <=  angles[i]) {
targetObj.angle = angles[i];
break;
}
}
});``````
``````<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download