Skip to main content

使用 Konva 在 HTML5 Canvas 上跳形状探戈

使用 Konva 在 HTML5 Canvas 上跳形状探戈

此演示展示了如何创建触发时围绕画布跳舞的动画形状。它演示了:

  1. 创建具有不同属性的随机形状
  2. 使用 Konva 的补间系统实现平滑动画
  3. 处理用户交互(拖放、按钮点击)
  4. 同时管理多个动画

使用说明: 拖放形状以调整位置,然后点击 “Tango!” 按钮让它们在画布上跳舞。每个形状将移动到随机位置,旋转,改变大小和颜色。刷新页面以生成新的随机形状。

import Konva from 'konva';

// 创建按钮
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();
  });
}

// 创建初始形状
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));