拖拽图片

获取Konva最新的信息

图片也支持拖拽,我们只需要设置图片的 draggable 属性为 true, 或者使用 draggable() 方法设置。

draggable() 方法会自动适配桌面端和移动端。

Konva Drag and Drop an Image Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Drag and Drop an Image 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;

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

var layer = new Konva.Layer();
// darth vader
var darthVaderImg = new Konva.Image({
image: imageObj,
x: stage.width() / 2 - 200 / 2,
y: stage.height() / 2 - 137 / 2,
width: 200,
height: 137,
draggable: true
});

// add cursor styling
darthVaderImg.on('mouseover', function() {
document.body.style.cursor = 'pointer';
});
darthVaderImg.on('mouseout', function() {
document.body.style.cursor = 'default';
});

layer.add(darthVaderImg);
stage.add(layer);
}
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = '/assets/darth-vader.jpg';
</script>
</body>
</html>