Skip to main content

HTML5 Canvas Select Shape by Type Tutorial

To select shapes by type with Konva, we can use the find() method with the name of the type or class name. The find() method returns an array of nodes that match the selector string.

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 shapes of different types
const circle1 = new Konva.Circle({
  x: 50,
  y: stage.height() / 2,
  radius: 30,
  fill: 'red'
});

const circle2 = new Konva.Circle({
  x: 150,
  y: stage.height() / 2,
  radius: 30,
  fill: 'green'
});

const rect = new Konva.Rect({
  x: 250,
  y: stage.height() / 2 - 25,
  width: 50,
  height: 50,
  fill: 'blue'
});

layer.add(circle1);
layer.add(circle2);
layer.add(rect);

// find all circles by type
const circles = layer.find('Circle');
circles.forEach(circle => {
  // add animation to circles only
  circle.to({
    duration: 1,
    scale: { x: 1.5, y: 1.5 },
    easing: Konva.Easings.EaseInOut
  });
});