HTML5 Canvas Optimizing Strokes Performance Tip

获取Konva最新的信息

Remove stroke from hit

If you have a shape with fill and very small stroke you can set shape.hitStrokeWidth(0) to remove stroke from hit graph.
Don’t use this property if your stroke is critical for hit detection (like non closed lines).

Disable shadow for stroke

If you don’t really need shadow for stroke you can set shape.shadowForStrokeEnabled(false).
Remember that shadow will be disable if you are using Konva.Line without fill.

Konva Optimizing Strokes Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Optimizing Strokes 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();
stage.add(layer);

var n = 100,
shape;
for (var i = 0; i < n; i++) {
shape = new Konva.Circle({
x: stage.width() * Math.random(),
y: stage.height() * Math.random(),
radius: 10 + 10 * Math.random(),
fill: Konva.Util.getRandomColor(),
stroke: 'black',
shadowColor: 'black',
draggable: true,
shadowOffset: {
x: 5,
y: 5
}
});
layer.add(shape);
}

var drawTimes = 30;
console.time('default params');
for (i = 0; i < drawTimes; i++) {
layer.draw();
}
console.timeEnd('default params');

layer.children.each(function(shape) {
shape.hitStrokeWidth(0);
});

console.time('hitStrokeWidth = 0');
for (i = 0; i < drawTimes; i++) {
layer.draw();
}
console.timeEnd('hitStrokeWidth = 0');

layer.children.each(function(shape) {
shape.hitStrokeWidth('auto');
shape.shadowForStrokeEnabled(false);
});

console.time('shadowForStrokeEnabled = false');
for (i = 0; i < drawTimes; i++) {
layer.draw();
}
console.timeEnd('shadowForStrokeEnabled = false');

layer.children.each(function(shape) {
shape.hitStrokeWidth(0);
shape.shadowForStrokeEnabled(false);
});

console.time('shadowForStrokeEnabled = false, hitStrokeWidth = 0');
for (i = 0; i < drawTimes; i++) {
layer.draw();
}
console.timeEnd('shadowForStrokeEnabled = false, hitStrokeWidth = 0');
</script>
</body>
</html>