Vardan Betikyan
Vardan Betikyan

Reputation: 394

Performance: Html5 Canvas / Javascript - Moving the background image using canvas.drawImage vs canvas.style

I have a background that scrolls up, down, left and right based on position, and was wondering if there is any significant performance difference into using drawImage() every time the position changes vs just drawing the entire background once and moving the canvas around using canvas.style

Using canvas.drawImage()

//cut piece and draw image to fill canvas every time position changes
canvas.drawImage(backgroundImg, 0 + positionX, 0 + positionY, c.width, c.height, 0, 0, c.width, c.height);

VS

Using canvas.style

canvas.width  = widthofbackgroundImg;
canvas.height = heightofbackgroundImg;

//draw entire background only once
canvas.drawImage(backgroundImg, 0, 0, widthofbackgroundImg, heightofbackgroundImg);

..then

//move the entire canvas on every position change
canvas.style.left = positionX;
canvas.style.up   = positionY;

Upvotes: 0

Views: 150

Answers (1)

Matthi
Matthi

Reputation: 1063

Those are two different approaches which are depending on the browser processing (different browsers might set different priorities in rendering). For sure, it does not make sense to move the canvas image by drawImage, if nothing else changes and there is just an initial draw. Instead of going with canvas.style.left and canvas.style.right I would suggest you to use transform = translate3d(x, y, 0) and test the performance improvement with your dev tools. This will be rendered via the GPU and may increase speed. It will prevent reflow which is time consuming in general. Also the reading from and writing to the DOM in alternation might slow down performance. It will help to first make all reading (get positions, scroll position or the like), save it in variables and then write everything.

Upvotes: 1

Related Questions