Skip to main content

How to implement drag and drop for canvas shapes with Vue?

To enable drag&drop for any node on canvas you just need to pass draggable: true property into the component.

When you drag&drop a shape, it is recommended to save its position in your app store. You can use dragstart and dragend events for that purpose.

Instructions: Try to drag the text. Notice how it changes color while being dragged.

<template>
<v-stage ref="stage" :config="stageSize">
<v-layer ref="layer">
<v-text
@dragstart="handleDragStart"
@dragend="handleDragEnd"
:config="{
text: 'Draggable Text',
x: 50,
y: 50,
draggable: true,
fill: isDragging ? 'green' : 'black'
}"
/>
</v-layer>
</v-stage>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;

export default {
data() {
return {
stageSize: {
width: width,
height: height
},
isDragging: false
};
},
methods: {
handleDragStart() {
this.isDragging = true;
},
handleDragEnd() {
this.isDragging = false;
}
}
};
</script>