跳到主要内容

HTML5 Canvas Konva 缩放动画教程

如需使用 Konva 为图形的缩放设置动画,可以通过 Konva.Animation 创建新动画,并定义一个在每一帧修改图形缩放比例的函数。

本教程将缩放蓝色六边形的 x 和 y 分量、黄色六边形的 y 分量, 以及红色六边形的 x 分量。红色六边形围绕位于图形右侧的轴缩放。

操作说明: 在六边形播放动画时拖放它们。

如需查看完整的属性和方法列表,请参阅 Konva.Animation 文档

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

// blue hexagon - scale x and y
const blueHex = new Konva.RegularPolygon({
x: 50,
y: 50,
sides: 6,
radius: 20,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

// yellow hexagon - scale y only
const yellowHex = new Konva.RegularPolygon({
x: 150,
y: 50,
sides: 6,
radius: 20,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

// red hexagon - scale x only
const redHex = new Konva.RegularPolygon({
x: 250,
y: 50,
sides: 6,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

layer.add(blueHex);
layer.add(yellowHex);
layer.add(redHex);

const period = 2000;

const anim = new Konva.Animation(function(frame) {
const scale = Math.sin(frame.time * 2 * Math.PI / period) + 2;

// blue hex - scale x and y
blueHex.scale({ x: scale, y: scale });

// yellow hex - scale y only
yellowHex.scaleY(scale);

// red hex - scale x only
redHex.scaleX(scale);
}, layer);

anim.start();