跳到主要内容

使用 Konva 创建 HTML5 Canvas 图形探戈

使用 Konva 创建 HTML5 Canvas 图形探戈

此示例展示如何创建触发后在 Canvas 上舞动的动画图形。它演示以下内容:

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

操作说明: 拖放图形以确定其位置,然后单击“Tango!”按钮,让它们在 Canvas 上舞动。每个图形都会移动到随机位置,并改变旋转角度、大小和颜色。刷新页面以生成新的随机图形。

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));