跳到主要内容

HTML5 Canvas 按 id 选择图形教程

要使用 Konva 按 id 选择图形,可以配合 # 选择器使用 find() 方法。 find() 方法始终返回元素数组,即使预计它只返回一个元素。 如果只需要一个元素,可以使用 findOne() 方法。 find() 方法适用于任何节点,包括舞台、图层、组和图形。

**操作说明:**按下“Activate Rectangle”按钮,按 id 选择矩形并执行过渡。你也可以拖放该矩形。

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

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

// create a rectangle with id
const rect = new Konva.Rect({
  x: stage.width() / 2 - 25,
  y: stage.height() / 2 - 25,
  width: 50,
  height: 50,
  fill: 'red',
  id: 'myRect',
  draggable: true
});

layer.add(rect);

// add button
const button = document.createElement('button');
button.textContent = 'Activate Rectangle';
document.body.appendChild(button);

button.addEventListener('click', () => {
  // find rectangle by id and animate it
  const rectangle = layer.findOne('#myRect');
  rectangle.to({
    duration: 1,
    rotation: 360,
    fill: 'blue',
    easing: Konva.Easings.EaseInOut
  });
});