Faster than save/restore HTML5 canvas
const canvas = document.createElement('canvas')
const c = canvas.getContext('2d')
canvas.width = innerWidth
canvas.height = innerHeight
document.body.append(canvas)
c.fillStyle = 'black'
c.fillRect(0, 0, canvas.width, canvas.height)
class Shooter {
constructor() {
this.x = innerWidth / 2
this.y = innerHeight / 2
this.vx = Math.random() * 10 - 5
this.vy = Math.random() * 10 - 5
this.color = 'rgba(255, 0, 0, 0.5)'
this.size = 10
this.halfSize = this.size / 2
}
draw() {
this.x += this.vx
this.y += this.vy
if (this.x < 0) {
this.x = innerWidth
} else if (this.x > innerWidth) {
this.x = 0
}
if (this.y < 0) {
this.y = innerHeight
} else if (this.y > innerHeight) {
this.y = 0
}
c.fillStyle = this.color
c.translate(this.x, this.y)
c.fillRect(-this.halfSize, -this.halfSize, this.size, this.size)
c.setTransform(1, 0, 0, 1, 0, 0)
}
}
const NUM = 1000
const shooters = []
for (let i = 0; i < NUM; i++) {
shooters.push(new Shooter())
}
function loop() {
c.fillStyle = 'rgba(0, 0, 0, 0.1)'
c.fillRect(0, 0, innerWidth, innerHeight)
for (let i = 0; i < NUM; i++) {
shooters[i].draw()
}
requestAnimationFrame(loop)
}
loop()
Using setTransform(1, 0, 0, 1, 0, 0)
is faster than using save
and restore
. If you don’t need to save context info like fills, line styles etc… consider this method.