Skip to main content

HTML5 Canvas Force Update Tutorial

Konva.Transformer automatically tracks properties of attached nodes. So it will adopt its own properties automatically.

Since Konva 10.7.1, the transformer also follows changes inside an attached Konva.Group: a child that changes size, or a child that is added or removed. In older versions, you had to call forceUpdate for these changes, as the demo below does.

But Konva.Transformer can not detect a change that sets no attribute. For example, a Konva.Line points array that you mutate in place, or a custom getSelfRect() that depends on outside state. After such a change, call the forceUpdate method to reset the transforming tools.

Instructions: Click the button. See how transformer is changed.

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 group = new Konva.Group({
x: 50,
y: 50,
draggable: true,
});
layer.add(group);

const text = new Konva.Text({
text: 'Some text here',
fontSize: 24,
});
group.add(text);

const rect = new Konva.Rect({
width: text.width(),
height: text.height(),
fill: 'yellow',
});
group.add(rect);

// add the shape to the layer
rect.moveToBottom();

const tr = new Konva.Transformer({
nodes: [group],
padding: 5,
// enable only one anchor
enabledAnchors: ['middle-left', 'middle-right'],
});
layer.add(tr);

const button = document.createElement('button');
button.innerHTML = 'Change text';
document.body.appendChild(button);
button.addEventListener('click', () => {
text.text('Something else is here');
rect.width(text.width());
// we need to update transformer manually
tr.forceUpdate();
});