Skip to main content

HTML5 Canvas Shape Resize Snapping

In some applications, you may want to snap resizing near some values. Snapping makes a shape "sticky" near provided values and works like rounding. You can control anchor position behavior with anchorDragBoundFunc method.

transformer.anchorDragBoundFunc(function (oldAbsPos, newAbsPos, event) {
// limit any another position on the x axis
return {
x: 0,
y: newAbsolutePosition.y,
};
});

Instructions: Try to resize a shape. You will see how transformer is trying to snap to guide lines.

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

// create guides

const horizontalLine = new Konva.Line({
points: [0, height / 2, width, height / 2],
stroke: '#000',
strokeWidth: 1,
dash: [4, 4],
});
layer.add(horizontalLine);

const verticalLine = new Konva.Line({
points: [width / 2, 0, width / 2, height],
stroke: '#000',
strokeWidth: 1,
dash: [4, 4],
});
layer.add(verticalLine);

const rect = new Konva.Rect({
x: 60,
y: 60,
width: 100,
height: 100,
fill: 'red',
draggable: true,
});
layer.add(rect);

const tr = new Konva.Transformer({
nodes: [rect],
anchorDragBoundFunc: function (oldPos, newPos) {
const dist = Math.sqrt(Math.pow(newPos.x - width / 2, 2));
if (dist < 10) {
return {
...newPos,
x: width / 2,
};
}
return newPos;
},
});
layer.add(tr);


</rewritten_file>