Skip to main content

How to flip shapes or image on canvas?

Is it possible mirror shapes vertically or horizontally?​

To flip any node with Konva you can use negative scaleX to flip it horizontally or scaleY to flip it vertically.

Remember that scale properties are working relative to origin of a node. For example for rectangle it will be top-left corner, for circle it will be its center. If you want to change origin of a node you can use offsetX and offsetY properties. To better understanding origin and offset, take a look into Position vs Offset post.

Depending on your use case, you may need to manually change {x, y} properties of the node to keep it on its original position after the scale.

Instructions: click on flip button, see how they are mirrored.

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(),
    });
  });
});