HTML5 Canvas Animate Position Tutorial

获取Konva最新的信息

To animate a shape’s position with Konva, we can create a new animation with Konva.Animation
which modifies the shape’s position with each animation frame.

For a full list of attributes and methods, check out the Konva.Animation documentation.

Konva Animate Position Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Animate Position 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();

var hexagon = new Konva.RegularPolygon({
x: stage.width() / 2,
y: stage.height() / 2,
sides: 6,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});

layer.add(hexagon);
stage.add(layer);

var amplitude = 100;
var period = 2000;
// in ms
var centerX = stage.width() / 2;

var anim = new Konva.Animation(function(frame) {
hexagon.x(
amplitude * Math.sin((frame.time * 2 * Math.PI) / period) + centerX
);
}, layer);

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