Skip to main content

HTML5 Canvas Select Shape by id Tutorial

To select a shape by id with Konva, we can use the find() method using the # selector. The find() method always returns an array of elements, even if we are expecting it to return one element. if you need only one element you can use findOne() method. The find() method works for any node, including the stage, layers, groups, and shapes.

Instructions: press the "Activate Rectangle" button to select the rectangle by id and perform a transition. You can also drag and drop the rectangle.

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
  });
});