今天一个偶然的几乎,发现一个怪异现象。因而探究了一下,有点意思,与君共勉。html
咱们都知道,Canvas的绘制,会受硬件影响。不一样的硬件设备会有明显的性能上的差别引发卡顿。可是如何影响的呢?canvas
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="canvas" style="width: 600px; height: 400px;"></div>
<script src="ryou-test.js"></script>
<script src="example.js"></script>
</body>
</html>
复制代码
(function(global) {
const RyouList = global.RyouList = function (dom, opts) {
this._root = dom;
this._options = {
ratio: 1,
...opts
};
this._init();
this._shouldUpdate = false;
this._eles = [];
}
RyouList.prototype._init = function () {
const ret = this._root.getBoundingClientRect();
const _div = document.createElement("div");
const _cvs = document.createElement("canvas");
this._ctx = _cvs.getContext("2d");
_div.appendChild(_cvs);
_div.style.width = ret.width + 'px';
_div.style.height = ret.height + 'px';
_cvs.width = ret.width * this._options.ratio;
_cvs.height = ret.height * this._options.ratio;
this._rect = {
width: _cvs.width,
height: _cvs.height
}
this._root.appendChild(_div);
}
RyouList.prototype.render = function () {
this._ctx.clearRect(0, 0, this._rect.width, this._rect.height);
const len = this._eles.length;
for (let i = 0; i < len; i++) {
this._ctx.beginPath();
this._ctx.fillStyle = "#0f0";
this._ctx.arc(this._eles[i].x, this._eles[i].y, this._eles[i].r, 0, 2 * Math.PI);
this._ctx.fill();
}
}
RyouList.prototype.add = function () {
this._shouldUpdate = true;
let x = Math.random() * this._rect.width;
let y = Math.random() * this._rect.height;
this._eles.push({
type: "cicle",
x: x,
y: y,
r: 5
})
}
}(window))
const rc = new RyouList(document.getElementById("canvas"));
for (let i = 0; i < 26929; i++) { // ---》 注意这个for循环。
rc.add();
}
let first = new Date().getTime()
rc.render();
console.log(new Date().getTime() - first)
复制代码
这是一个颇有意思的事情,由于个人代码仅仅记录了for循环建立路径打印这一过程,所以是不受建立元素,计算随机位置的影响的,去掉for循环的性能影响,基本上是比较接近Canvas的渲染消耗的。app
是否是颇有意思?Canvas的性能降低并非线性的,而是以指数级的。在达到某个值的时候,这个性能会指数级降低dom
是否是颇有意思?经过以上测试,Canvas的渲染并非受咱们绘制多少图形影响。性能
再一次证实,Canvas的渲染并非受咱们绘制多少图形影响的。测试
以上4次实验,发现,咱们在Canvas绘制多少次对性能的直接影响其实并不大,可是咱们增大每次绘制的图形的大小的时候,性能会严重影响。ui
因此,Canvas性能的直接影响因素应该是咱们绘制的【像素总数】,而不是绘制的元素数量。当咱们绘制的像素总数达到一个阈值,那么Canvas的性能会指数级降低,这个阈值极可能就是由硬件决定的。this