Canvas vs SVG for simple games

user1551120 picture user1551120 · Sep 5, 2012 · Viewed 12.2k times · Source

If I wanted to build a simple game (snake, checkers, pacman or whatever) what would be the better approach - SVG or Canvas ?

Things I'm interested in:

  1. Ease of implementation (learning curve of Canvas vs SVG) . For example if SVG has significantly less tutorials and community support that's crucial to me.

  2. Performance (not critical to me but still important)

And also , in the gaming field , are there specific games that SVG is more suited for than Canvas (or vice versa?)

Answer

methodofaction picture methodofaction · Sep 6, 2012

Games that require a lot of mouse interaction and not much continuous animation (such as checkers or chess, or any board game for that matter) are better suited for SVG because you work with dom elements. Consider a simple button hover, in SVG you can add event listeners or even just place g.button:hover path {fill: blue;} in your CSS and it will work. Canvas, on the other hand, requires keeping track of the hit area and drawing everything in Javascript.

Snake and Pacman would be better suited for canvas, you control everything with your keyboard and painting to canvas is less expensive than moving elements around in SVG. There are excellent gaming libraries for canvas, impact.js is one of them.

Addressing your points:

Ease of use: if you are familiar with pure javascript DOM manipulation SVG is a breeze. If you are blank slate I'd say canvas is easier to grasp, as you just paint on it.

Community support: for gaming canvas wins hands down. There is a strong SVG community but not in the gaming area.

Performance: Mixed. Both canvas and SVG can be slow if you don't pull off a couple of tricks. For example, moving a single square from left to right can be jerky in canvas if you repaint the entire screen on each frame. If you just repaint the area that changed then it's smooth. SVG would handle this case without a hitch. But on the other hand, if you want to animate thousands of rectangles at once, canvas handles it smoothly and SVG bogs down if you don't wrap the rects in a group and move the group around.

All in all, if you want to explore gaming in javascript perhaps Canvas is a better option. I've done three games in SVG, the latest one being http://color.method.ac, but I've dabbled in canvas and I think it's better suited for gaming.