HTML5 Canvas Drag and Drop an Image
To drag and drop an image with Konva, we can set the draggable
property
to true when we instantiate a shape, or we can use the draggable()
method.
The draggable()
method enables drag and drop for both desktop and mobile
applications automatically.
- Vanilla
- React
- Vue
import Konva from 'konva'; const stage = new Konva.Stage({ container: 'container', width: window.innerWidth, height: window.innerHeight, }); const layer = new Konva.Layer(); const imageObj = new Image(); imageObj.onload = () => { const yoda = new Konva.Image({ x: 50, y: 50, image: imageObj, width: 106, height: 118, draggable: true, }); // add cursor styling yoda.on('mouseover', function () { document.body.style.cursor = 'pointer'; }); yoda.on('mouseout', function () { document.body.style.cursor = 'default'; }); layer.add(yoda); layer.draw(); }; imageObj.src = 'https://konvajs.org/assets/yoda.jpg'; stage.add(layer);
import { Stage, Layer, Image } from 'react-konva'; import { useImage } from 'react-konva'; const App = () => { const [image] = useImage('https://konvajs.org/assets/yoda.jpg'); return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> {image && ( <Image x={50} y={50} image={image} width={106} height={118} draggable onMouseEnter={(e) => { document.body.style.cursor = 'pointer'; }} onMouseLeave={(e) => { document.body.style.cursor = 'default'; }} /> )} </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-image v-if="image" :config="imageConfig" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave" /> </v-layer> </v-stage> </template> <script setup> import { ref, onMounted } from 'vue'; const stageSize = { width: window.innerWidth, height: window.innerHeight }; const image = ref(null); onMounted(() => { const imageObj = new Image(); imageObj.src = 'https://konvajs.org/assets/yoda.jpg'; imageObj.onload = () => { image.value = imageObj; }; }); const imageConfig = { x: 50, y: 50, image: image, width: 106, height: 118, draggable: true }; const handleMouseEnter = () => { document.body.style.cursor = 'pointer'; }; const handleMouseLeave = () => { document.body.style.cursor = 'default'; }; </script>