title: HTML5 Canvas Simple Drag Bounds Tutorial

To restrict the movement of shapes being dragged and dropped with Konva,
we can use the dragmove event and overrides the drag and drop position inside of it.

This event can be used to constrain the drag and drop movement in all kinds of ways, such as constraining the motion horizontally, vertically, diagonally, or radially, or even constrain the node
to stay inside of a box, circle, or any other path.

shape.on('dragmove', () => {
// lock position of the shape on x axis
// keep y position as is
shape.x(0);
});

Tip: you can use shape.absolutePosition() method to get/set absolute position of a node, instead of relative x and y.

Instructions: Drag and drop the the horizontal text and observe that it can only
move horizontally. Drag and drop the vertical text and observe that it can only move vertically.

Konva Simple Drag Bounds Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Simple Drag Bounds Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

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

var layer = new Konva.Layer();
// add the layer to the stage
stage.add(layer);

var rectHeight = 50;
var rectY = (stage.height() - rectHeight) / 2;

var hbox = new Konva.Text({
x: 20,
y: 70,
fontSize: 24,
fontFamily: 'Calibri',
text: 'horizontal',
fill: 'black',
padding: 15,
draggable: true,
dragBoundFunc: function (pos) {
return {
x: pos.x,
y: this.absolutePosition().y,
};
},
});
layer.add(hbox);
var originalY = hbox.y();
hbox.on('dragmove', () => {
// we will keep new x position
// but reset y position to the original
hbox.y(originalY);
});

var vbox = new Konva.Text({
x: 150,
y: 70,
draggable: true,
fontSize: 24,
fontFamily: 'Calibri',
text: 'vertical',
fill: 'black',
padding: 15,
});
layer.add(vbox);
var originalX = vbox.x();
vbox.on('dragmove', () => {
// we will keep new x position
// but reset y position to the original
vbox.x(originalX);
});
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.