HTML5 Canvas Simple Drag Bounds Tutorial

To restrict the movement of shapes being dragged and dropped with Konva,
we can use the dragBoundsFunc property which is a user defined function that
overrides the drag and drop position. This function 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.

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://cdn.rawgit.com/konvajs/konva/1.7.6/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();

var rectHeight = 50;
var rectWidth = 100;
var rectY = (stage.getHeight() - 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.getAbsolutePosition().y
}
}
});

var vbox = new Konva.Text({
x: 150,
y: 70,
draggable: true,
fontSize: 24,
fontFamily: 'Calibri',
text: 'vertical',
fill: 'black',
padding: 15,
draggable: true,
dragBoundFunc: function(pos) {
return {
x: this.getAbsolutePosition().x,
y: pos.y
}
}
});

layer.add(hbox);
layer.add(vbox);
// add the layer to the stage
stage.add(layer);
</script>

</body>
</html>