我需要在 HTML5 canvas 上绘制很多点,这需要很长时间。我的代码如下所示:
var points = getPoints() // Array of {x,y,color}
var ctx = canvas.getContext("2d");
for (var i = 0; i < points.length; i++) {
ctx.fillStyle = points[i].color
ctx.beginPath()
ctx.arc(points[i].x, points[i].y, radius, 0, Math.PI * 2, true)
ctx.fill() }
我想知道我可以做哪些性能调整来加快速度。我只有5种不同的颜色。例如,如果我对点列表进行动态排序以仅更改 ctx.fillStyle
5 次而不是每个点一次,我是否会受益?
最佳答案
For example, would I benefit form sorting the points list on-the-fly to change ctx.fillStyle only 5 times instead of one time per point?
根据我的经验,是的 - 频繁更改 .fillStyle
是非常昂贵的。
我的代码在 Canvas 上绘制大量矩形,绘制仅包含两种不经常变化颜色的矩形的时间明显优于绘制许多频繁变化颜色的矩形。
无论如何,因为你只有五种不同的颜色:
- 创建一个离屏 Canvas ,您可以在其中绘制五个圆圈
- 使用
.drawImage()
将正确的色圈 blit 到目标 Canvas 中,而无需重新计算弧坐标 - 将
points[i]
分配给循环内的局部变量,以避免反复取消引用它。
在我的笔记本电脑上,这段代码在 7 毫秒内在 400x400 的 Canvas 上绘制了 3000 个圆圈:
var colours = ['red', 'green', 'blue', 'yellow', 'magenta'];
var n = colours.length;
var r = 10;
var d = r * 2;
var off = document.createElement('canvas');
off.width = n * d;
off.height = d;
var ctx = off.getContext('2d');
for (var i = 0; i < n; ++i) {
ctx.fillStyle = colours[i];
ctx.beginPath();
ctx.arc(i * d + r, r, r, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
var canvas = document.getElementById('canvas');
var ctx2 = canvas.getContext('2d');
var t0 = Date.now();
for (var i = 0; i < 3000; ++i) {
var c = Math.floor(n * Math.random());
var x = Math.floor(canvas.width * Math.random());
var y = Math.floor(canvas.height * Math.random());
ctx2.drawImage(off, c * d, d, d, x - r, y - r, d, d);
}
var t1 = Date.now();
alert((t1 - t0) + "ms");
关于javascript - 加速在 HTML5 canvas 元素上绘制多个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13916066/