Speeding Up Line Drawing on HTML5 Canvas

A while ago (maybe a year) I made a crappy little game called Space Cave. It's nothing special, mainly just programmed it to learn about the HTML5 canvas and how to interact with it using Javascript + jQuery.

The game basically draws a bunch of lines and the player cannot let a spaceship come into contact with the ends of the lines.  The initial version was super slow and choppy, so I recently decided to speed it up a bit.

Double Buffering

Double buffer by drawing changes to a canvas created in Javascript, then draw that canvas on the main one.  This improved smoothness quite a bit.

Clearing the Canvas

There is a lot of conflicting information about this, likely just from differences in browsers. From what I've read, there are two ways to clear a canvas: clearRect(...) and resetting the canvas width. Some sites say never reset the width, some say it's alright but not ideal, some say it's the best way.

In the end I just went with clearRect(), it works fairly quickly on all the browsers I've tried. Resetting the width honestly seems like a dirty hack.

Window.requestAnimationFrame(...)

Instead of setting a timeout of 1000/fps to call a draw method, some websites say simply calling this method is faster. I honestly didn't do much of a scientific test, but when I first made the game it seemed that setTimeout was smoother. Now when I go back and use this method it does seem a bit smoother. Possibly a difference in the browser versions? It's a mystery :)

No comments:

Post a Comment