HTML5 Canvas Konva 缩放动画教程

要使用 Konva 为形状的缩放做动画,我们可以创建一个新的动画 Konva.Animation,并定义一个函数,在每一帧动画中修改形状的缩放。

在本教程中,我们将对一个蓝色六边形的 x 和 y 分量,黄色六边形的 y 分量,以及红色六边形的 x 分量进行缩放,缩放围绕位于形状右侧的一个轴心进行。

说明:在动画过程中拖动并放置六边形

欲查看完整的属性和方法列表,请访问 Konva.Animation 文档

Konva 缩放动画演示view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Scale Animation Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

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

var layer = new Konva.Layer();

/*
* leave center point positioned
* at the default which is at the center
* of the hexagon
*/
var blueHex = new Konva.RegularPolygon({
x: 50,
y: stage.height() / 2,
sides: 6,
radius: 40,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

var yellowHex = new Konva.RegularPolygon({
x: 150,
y: stage.height() / 2,
sides: 6,
radius: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

/*
* move center point to right side
* of hexagon
*/
var redHex = new Konva.RegularPolygon({
x: 300,
y: stage.height() / 2,
sides: 6,
radius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 50,
y: 0,
},
draggable: true,
});

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

var period = 2000;

var anim = new Konva.Animation(function (frame) {
var scale = Math.sin((frame.time * 2 * Math.PI) / period) + 0.001;
// scale x and y
blueHex.scale({ x: scale, y: scale });
// scale only y
yellowHex.scaleY(scale);
// scale only x
redHex.scaleX(scale);
}, layer);

anim.start();
</script>
</body>
</html>