HTML5 Canvas 形状重绘性能提示

重要说明:我认为使用这样的技巧是一种反模式。你应该避免使用它。

通常,当你需要更新画布时,你应该调用 layer.draw()

但是在少数情况下,可以更新 Konva.Node 而无需更新整个图层。你可以调用 shape.draw()但请记住,在这种情况下,形状将被绘制在现有画布之上
因此,如果你的节点应该放在其他节点之下或者具有不透明度,则无法使用这个提示。

说明:将鼠标悬停在框上以进行高亮显示。

Konva Shape Redraw Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Shape Redraw Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
// disable automatic redraw
Konva.autoDrawEnabled = false;
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 BOX_SIZE = 15;
var box;
// generate boxes
for (var ix = 0; ix < width / BOX_SIZE; ix++) {
for (var iy = 0; iy < height / BOX_SIZE; iy++) {
box = new Konva.Rect({
x: ix * BOX_SIZE,
y: iy * BOX_SIZE,
width: BOX_SIZE - 1,
height: BOX_SIZE - 1,
fill: 'darkgrey',
stroke: 'white',
});
layer.add(box);
}
}
layer.draw();

// as all boxes stay separately with no overlap
// and they have no opacity
// we can call 'box.draw()' and we will have expected result
// REMEMBER that is this case box will be drawn on top of existing layer
// without clearing
layer.on('mouseover', function (evt) {
var box = evt.target;
box.fill('#E5FF80');
box.draw();
});
layer.on('mouseout', function (evt) {
var box = evt.target;
box.fill('darkgrey');
box.draw();
});
</script>
</body>
</html>