跳到主要内容

如何将 DOM 图像拖放到 Canvas

此示例演示如何将 Canvas 外部的 DOM 元素放到舞台中。

第一个图像是 DOM 图像。可以使用 HTML5 拖放 启用拖动功能。

要在触摸设备上为 DOM 元素启用拖放,需要执行一些额外步骤。有关详细信息,请阅读此文

**操作说明:**将尤达拖放到 Canvas 中。

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

// Add DOM elements to render outside the container
document.getElementById('container').insertAdjacentHTML(
  'beforebegin',
  `
  <p>Drag&drop yoda into the grey area.</p>
  <div id="drag-items">
    <img src="https://konvajs.org/assets/yoda.jpg" draggable="true" style="height: 100px; margin: 5px;" />
    <img src="https://konvajs.org/assets/darth-vader.jpg" draggable="true" style="height: 100px; margin: 5px;" />
  </div>
`
);

// Style the container with grey background
document.getElementById('container').style.backgroundColor = 'rgba(0, 0, 0, 0.1)';

// Create stage and layer
const stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height - 150, // leave space for the DOM elements
});

const layer = new Konva.Layer();
stage.add(layer);

// Track URL of the dragging element
let itemURL = '';
document
  .getElementById('drag-items')
  .addEventListener('dragstart', function (e) {
    itemURL = e.target.src;
  });

// Handle dragover on container
const container = stage.container();
container.addEventListener('dragover', function (e) {
  e.preventDefault(); // important - must prevent default behavior
});

// Handle drop on container
container.addEventListener('drop', function (e) {
  e.preventDefault();
  
  // Register the pointer position manually since this is a DOM event
  stage.setPointersPositions(e);
  
  // Load the image and add it to the layer
  Konva.Image.fromURL(itemURL, function (image) {
    // Calculate appropriate size based on image dimensions
    const img = image.image();
    const maxDimension = 100;
    let width = img.width;
    let height = img.height;
    
    if (width > height) {
      height = (height / width) * maxDimension;
      width = maxDimension;
    } else {
      width = (width / height) * maxDimension;
      height = maxDimension;
    }
    
    image.size({
      width: width,
      height: height
    });
    
    layer.add(image);
    image.position(stage.getPointerPosition());
    image.draggable(true);
  });
});