Test name | Executions per second |
---|---|
Cached canvas | 24.2 Ops/sec |
Cached Path2D | 1949.9 Ops/sec |
<canvas height="500" width="500"/>
<canvas height="500" width="500"/>
var [canvas1, canvas2] = Array.from(document.querySelectorAll('canvas'));
var ctx1 = canvas1.getContext('2d')
var ctx2 = canvas2.getContext('2d')
var rects = new Array(100).fill(null).map(() => ({
x: Math.floor(Math.random() * 100),
y: Math.floor(Math.random() * 100),
width: Math.floor(Math.random() * 100) + 1,
height: Math.floor(Math.random() * 100) + 1
}))
for (var rect of rects) {
var cached = document.createElement('canvas')
cached.width = rect.width
cached.height = rect.height
rect.cached = cached.getContext('2d')
rect.cached.fillStyle = 'blue'
rect.cached.fillRect(0, 0, rect.width, rect.height)
ctx1.drawImage(rect.cached.canvas, rect.x, rect.y, rect.width, rect.height)
}
ctx1.clearRect(0, 0, 500, 500)
for (var rect of rects) {
ctx1.drawImage(rect.cached.canvas, rect.x, rect.y, rect.width, rect.height)
}
for (var rect of rects) {
rect.path = new Path2D()
rect.path.rect(rect.x, rect.y, rect.width, rect.height)
ctx2.fillStyle = rect.fill
ctx2.fill(rect.path)
}
ctx2.clearRect(0, 0, 500, 500)
for (var rect of rects) {
ctx2.fillStyle = 'red'
ctx2.fill(rect.path)
}