FabricJs rotate object without moving the position

Viewed 6817

I'm trying to set the angle to increments of 90 while keeping the position visually the same. I have it working but its really hacky. Can someone improve this code ex) without needing the switch statements. https://codesandbox.io/s/lx347ln669

2 Answers

triangle.rotate(angle);

Sets "angle" of an instance with centered rotation

Rotate in farbic.js docs

should rotate the triangle on it's central rotation. This acts differently to triangle.set('angle', 90) which seems to rotate based on the top left corner.

You may also find this useful if you want the user to use the default controls and 'snap to' your angles:

straighten(triangle);

Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)

Straighten in fabric.js docs

Try setting originX: 'center' and originY: 'center' when you create your triangle. No need to change the origins on each rotation.

var canvasEl = document.getElementById('c');
var canvas = new fabric.Canvas('c');
var triangle = new fabric.Triangle({
  width: 200,
  height: 200,
  fill: "blue",
  left: 50,
  top: 50,
  originX: "center",
  originY: "center"
});
canvas.add(triangle)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.6/fabric.min.js"></script>
<canvas id="c"></canvas>

Related