HTML5 Canvas Shape Caching Performance Tip

获取Konva最新的信息

One way to drastically improve drawing performance for complex Konva shapes is to cache them as images.
This can be achieved by using the cache() method to convert a node into an image object.

This particular tutorial of drawing 10 cached stars rather than drawing 10 individual
stars sees about a 4x drawing performance boost. Caching can be applied to any node,
including the stage, layers, groups, and shapes.

Note: The cache() method requires that the image is hosted on a web server with the same domain as the code executing it.

In same cases cache() function can not automatically detect size of node.
So you should be careful for groups and shapes with shadows and strokes.
If you see unexpected result pass bound properties to cache() function with x, y, width and height properties.

Konva Shape Caching Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Shape Caching 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 star = new Konva.Star({
innerRadius: 20,
outerRadius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 5,
numPoints: 5,
x: 60,
y: 60,
draggable: true,
shadowOffset: { x: 5, y: 5 },
shadowColor: 'black',
shadowBlur: 5,
shadowOpacity: 0.5
});

layer.add(star);
stage.add(layer);
star.cache();

var clone;
for (var n = 0; n < 10; n++) {
clone = star.clone({
x: Math.random() * stage.width(),
y: Math.random() * stage.height()
});
clone.cache();
layer.add(clone);
}

layer.draw();
</script>
</body>
</html>