Skip to main content

Canvas Flip Image — Mirror and Flip Shapes on HTML5 Canvas

Flip any image or shape on an HTML5 Canvas — horizontally, vertically, or both. This technique is essential for building image editors, design tools, and canvas-based applications where users need to mirror content.

To flip any node with Konva you can use negative scaleX to flip it horizontally or scaleY to flip it vertically. The scale properties work relative to the origin of a node. For a rectangle that's the top-left corner; for a circle it's the center. You can change the origin with offsetX and offsetY — see the Position vs Offset guide for details.

Depending on your use case, you may need to adjust {x, y} to keep the node in its original position after flipping.

Instructions: click the flip buttons to see shapes mirror horizontally and vertically.

import Konva from 'konva';

var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

var layer = new Konva.Layer();
stage.add(layer);

var text1 = new Konva.Text({
  x: 180,
  y: 50,
  text: 'Default text with no offset. Its origin is in top left corner.',
  align: 'center',
  width: 200,
});
layer.add(text1);

var text2 = new Konva.Text({
  text: 'Text with the origin in its center',
  width: 200,
  align: 'center',
  y: 100,
  x: 270,
});
layer.add(text2);
// set horizontal origin in the center of the text

text2.offsetX(text2.width() / 2);

var button = document.createElement('button');
button.innerText = 'Flip horizontally';
button.style.position = 'absolute';
button.style.top = '5px';
button.style.left = '5px';
document.body.appendChild(button);

button.addEventListener('click', () => {
  layer.find('Text').forEach((text) => {
    text.to({
      scaleX: -text.scaleX(),
    });
  });
});