Skip to main content

How to resize shape on canvas without changing its stroke size?

Remember, that Konva.Transformer is changing scaleX and scaleY properties of a node. By default, if you are transforming a shape, its stroke will be scaled too. In some cases that is not a good behavior.

There are two ways to prevent stroke scaling:

  1. Reset scale of a shape
  2. Use combination of shape.strokeScaleEnabled(false) and transformer.ignoreStroke(false)

Instructions: there are two rectangles to resize. The green one will reset its scale. The red one will just disable stroke scaling.

import Konva from 'konva';

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

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

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

// first way - reset scale on transform end

const rect1 = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: '#00ff00',
stroke: 'black',
strokeWidth: 5,
draggable: true,
});
layer.add(rect1);

const tr1 = new Konva.Transformer({
nodes: [rect1],
});
layer.add(tr1);

rect1.on('transformend', () => {
// after transform we need to reset scale

rect1.scaleX(1);
rect1.scaleY(1);
// and increase width and height manually

rect1.width(rect1.width() _ rect1.scaleX());
rect1.height(rect1.height() _ rect1.scaleY());
});

// second way - disable stroke scaling

const rect2 = new Konva.Rect({
x: 200,
y: 50,
width: 100,
height: 100,
fill: '#ff0000',
stroke: 'black',
strokeWidth: 5,
draggable: true,
strokeScaleEnabled: false,
});
layer.add(rect2);

const tr2 = new Konva.Transformer({
nodes: [rect2],
ignoreStroke: true,
});
layer.add(tr2);