跳到主要内容

HTML5 Canvas 拖放图像

如需使用 Konva 拖放图像,可以在创建图形时将 draggable 属性 设置为 true,也可以使用 draggable() 方法。 draggable() 方法会自动为桌面应用和移动应用启用拖放功能。

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);
};
imageObj.src = 'https://konvajs.org/assets/yoda.jpg';

stage.add(layer);