HTML5 Canvas Optimize Animation Performance Tip

If you animation have frames without any updates (no nodes are changed) you may return false from animation function.

In this case Konva wouldn’t update layers.

Konva Optimize Animation Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.0/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Optimize 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();
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;
// we have animation that do nothing in some cases
var anim = new Konva.Animation(function(frame) {
if ((frame.time % (period * 2)) < period) {
// regular update
hexagon.x(amplitude * Math.cos(frame.time * 2 * Math.PI / period) + centerX);
} else {
// this is "pause" phase
// we don't need update layer in this case
// so return false and Konva will skip layer draw
return false;
}
}, layer);
anim.start();
</script>
</body>
</html>