HTML5 画布层管理性能技巧

在创建 Konva 应用程序时,考虑性能时最重要的事情是层管理。 Konva 相较于其他画布库的一个显著特点是,它使我们能够创建独立的层,每层都有自己的画布元素。这意味着我们可以动画、过渡或更新某些舞台元素,而不必重新绘制其他元素。如果我们检查 Konva 舞台的 DOM,将会发现每层实际上都有一个画布元素。

这个教程有两个层,一个是动画层,另一个是包含文本的静态层。由于没有理由不断重新绘制文本,因此它被放置在自己的层中。

注意:不要创建太多层。通常 3-5 层为上限。

Konva 层管理演示view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Layer Management 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 animLayer = new Konva.Layer();
var staticLayer = new Konva.Layer();

/*
* leave center point positioned
* at the default which is at the center
* of the hexagon
*/

var blueHex = new Konva.RegularPolygon({
x: 50,
y: stage.height() / 2,
sides: 6,
radius: 40,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

var yellowHex = new Konva.RegularPolygon({
x: stage.width() / 2,
y: stage.height() / 2,
sides: 6,
radius: 30,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

/*
* move center point to right side
* of hexagon
*/
var redHex = new Konva.RegularPolygon({
x: 250,
y: stage.height() / 2,
sides: 6,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 30,
y: 0,
},
draggable: true,
});

var text = new Konva.Text({
x: 10,
y: 10,
text: 'Static Layer',
fontSize: '30',
fontFamily: 'Calibri',
fill: 'black',
});

staticLayer.add(text);

animLayer.add(blueHex, yellowHex, redHex);
stage.add(animLayer, staticLayer);

var period = 2000;
var anim = new Konva.Animation(function (frame) {
var scale = Math.sin((frame.time * 2 * Math.PI) / period) + 0.001;
// scale x and y
blueHex.scale({ x: scale, y: scale });
// scale only y
yellowHex.scaleY(scale);
// scale only x
redHex.scaleX(scale);
}, animLayer);

anim.start();
</script>
</body>
</html>