Skip to main content

How to resize text on canvas?

Remember, that Konva.Transformer is changing scaleX and scaleY properties of a node. If you want to change width of the text, without changing its size, you should reset scale of a text back to 1 and adjust width accordingly.

You can use transform event to update text's properties as you need it.

Instructions: Try to resize a text.

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);

const text = new Konva.Text({
x: 50,
y: 50,
text: 'Hello from Konva! Try to resize me.',
fontSize: 24,
draggable: true,
width: 200,
});
layer.add(text);

const tr = new Konva.Transformer({
nodes: [text],
// enable only one anchor to see better what is happening

// we are changing width only

enabledAnchors: ['middle-left', 'middle-right'],
});
layer.add(tr);

text.on('transform', function () {
// reset scale on transform

text.setAttrs({
width: text.width() \* text.scaleX(),
scaleX: 1,
});
});