HTML5 Canvas Animate Position Tutorial

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://cdn.rawgit.com/konvajs/konva/1.5.0/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.getWidth() / 2,
y: stage.getHeight() / 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.getWidth() / 2;
var anim = new Konva.Animation(function(frame) {
hexagon.setX(amplitude * Math.sin(frame.time * 2 * Math.PI / period) + centerX);
}, layer);
anim.start();
</script>
</body>
</html>