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.
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.