Skip to main content

HTML5 Canvas Select Shape by Name Tutorial

To select shapes by name with Konva, we can use the find() method using the . selector. 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 with names
const circle1 = new Konva.Circle({
x: 50,
y: stage.height() / 2,
radius: 30,
fill: 'red',
name: 'myCircle'
});

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

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

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

// find all circles by name
const circles = layer.find('.myCircle');
circles.forEach(circle => {
// add animation to circles only
circle.to({
duration: 1,
rotation: 360,
easing: Konva.Easings.EaseInOut
});
});