Skip to main content

Modify Shape Color on Click

Instructions: Click on a shape to change its color

import Konva from 'konva';

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

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

const layer = new Konva.Layer();

const triangle = new Konva.RegularPolygon({
  x: 80,
  y: 120,
  sides: 3,
  radius: 50,
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 4,
});

triangle.on('click', function () {
  const fill = this.fill() === 'yellow' ? '#00D2FF' : 'yellow';
  this.fill(fill);
});

layer.add(triangle);

const circle = new Konva.Circle({
  x: 180,
  y: 120,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});

circle.on('click', function () {
  const fill = this.fill() === 'red' ? '#00d00f' : 'red';
  this.fill(fill);
});

layer.add(circle);
stage.add(layer);