Skip to main content

HTML5 Canvas Shape Tango with Konva

HTML5 Canvas Shape Tango with Konva

This demo shows how to create animated shapes that dance around the canvas when triggered. It demonstrates:

  1. Creating random shapes with different properties
  2. Using Konva's tweening system for smooth animations
  3. Handling user interactions (drag and drop, button clicks)
  4. Managing multiple animations simultaneously
import Konva from 'konva';

// Create button
const button = document.createElement('button');
button.textContent = 'Tango!';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
button.style.padding = '10px';
document.body.appendChild(button);

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

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

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];

function getRandomColor() {
  return colors[Math.floor(Math.random() * colors.length)];
}

function tango(layer) {
  layer.getChildren().forEach((shape) => {
    const radius = Math.random() * 100 + 20;
    
    new Konva.Tween({
      node: shape,
      duration: 1,
      x: Math.random() * stage.width(),
      y: Math.random() * stage.height(),
      rotation: Math.random() * 360,
      radius: radius,
      opacity: (radius - 20) / 100,
      easing: Konva.Easings.EaseInOut,
      fill: getRandomColor(),
    }).play();
  });
}

// Create initial shapes
for (let n = 0; n < 10; n++) {
  const radius = Math.random() * 100 + 20;
  const shape = new Konva.RegularPolygon({
    x: Math.random() * stage.width(),
    y: Math.random() * stage.height(),
    sides: Math.ceil(Math.random() * 5 + 3),
    radius: radius,
    fill: getRandomColor(),
    opacity: (radius - 20) / 100,
    draggable: true,
  });

  layer.add(shape);
}

button.addEventListener('click', () => tango(layer));

Instructions: Drag and drop the shapes to position them, then click the "Tango!" button to make them dance around the canvas. Each shape will move to a random position, rotate, change size, and color. Refresh the page to generate new random shapes.