FabricJs FlipX FlipY Fix

Goal: To work similar to how you would expect i.e. How photoshop flips

by Steve Eberhardt

HTML

<h1>FlipX and FlipY Fix?</h1>
<h2>Issue:</h2>
<p>After rotating, FlipX and FlipY do not act the way you would expect as they ignore any rotation, flipping on the original axis.</p>
<h2>Goal:</h2>
<p>To work similar to how you would expect i.e. How photoshop flips</p> 

<canvas id="c" width="600" height="300"></canvas>
<button id="flipY">flipY</button>
<button id="flipX">flipX</button>
<p><b>Proposed Solution:</b> Get the current rotation angle, and apply the negative of that value on flip. </p>
<p><b>Current Issues:</b> <br>1. Flipped object's position changes, likely due to rotation.<br>
2. Controls sometimes get lost after flip. </p>

CSS

body {
  font-family: sans-serif;
}

#c {
  border: 1px solid black;
}

button {
  margin-top: 20px;
}

JavaScript

(function() {
    // Code from FabricJs tutorial - http://fabricjs.com/fabric-intro-part-1/#objects
    var canvas = new fabric.Canvas('c');
    
    // create a rectangle object
    var rect = new fabric.Rect({
      left: 100,
      top: 100,
      fill: 'red',
      width: 80,
      height: 40
    });
    
    var triangle = new fabric.Triangle({
      left: 100,
      top: 100,
      width: 40,
      height: 40,
      fill: 'blue'
    });
    
    var group = new fabric.Group([ rect, triangle ], {
    	originX: 'center',
      originY: 'center',
      left: 150,
      top: 100,
      angle: 20
    });
    
    // "add" rectangle onto canvas
    //canvas.add(rect);
    canvas.add(group);
    
    
    //rect.set({ strokeWidth: 5, stroke: 'rgba(100,200,200,0.5)' });
    //rect.set('angle', 15).set('flipY', true); // doesn't work
    group.set('flipX', true);
    group.setCoords();

    canvas.renderAll(); // this wasn't mentioned in the tutorial, but I'm pretty sure it's needed
    
    
    
    // Just toggling flipX and flipY
    document.getElementById('flipY').addEventListener('click', function () {
        group.toggle('flipY');
        var angle = group.get('angle')
        var negangle = 0 - angle;
        group.set("angle", negangle);
        group.setCoords();
        canvas.renderAll();
    });
    
    document.getElementById('flipX').addEventListener('click', function () {
        group.toggle('flipX');
        var angle = group.get('angle')
        var negangle = 0 - angle;
        group.set("angle", negangle);
        group.setCoords();
        canvas.renderAll();
    });
})();