Nov 24 2007
Browser 2D canvas and Sudoku
Graphics rendering support in browsers is getting better each day. From styled DIV elements to SVG to Apple’s Canvas. Though some may argue whether SVG is better or Canvas. From Wikipedia: “The canvas element is part of HTML5 and allows for dynamic scriptable rendering of bitmap images.” I played with the 2D capabilities of Canvas provided by Firefox and wrote a game of Sudoku.
Lets get down to writing some code. The rendering context of a canvas is obtained by calling its getContext() function. This context supports the drawing functions. A gradient-filled circle as an example:
HTML:
1 | <canvas id="board" width="200" height="200" style="border: 1px solid black"> </canvas> |
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 | var board = document.getElementById('board'); var ctx = board.getContext('2d'); // create a radial gradient from yellow to blue and set it as the fill style var g = ctx.createRadialGradient(100, 100, 10, 100, 100, 100); g.addColorStop(0, 'yellow'); g.addColorStop(1, 'blue'); ctx.fillStyle = g; // draw a filled circle at (100, 100) with r = 100 ctx.arc(100, 100, 100, 0, 2 * Math.PI, false); ctx.fill(); |
This is what we get:

You can visit the following links for more on Canvas:
Wikipedia entry
Apple developer documentation for Safari
Mozilla Canvas tutorial
Very good article on AMIS Technology blog
I used the 2D canvas to write a game of Sudoku. My focus was on the Canvas script. So I have not given much attention to the nitty gritties of Sudoku. It is playable except that the initial game board is random. So initial game boards may or may not be solvable. However, it won’t let you place a number if it is repeated in the same row, column or group. You can play the game here. The script file is located here.
Compatibility:
Works with Firefox 2.
Does not work with IE7.
If it works on other browsers, do let me know at abhijeet_maharana -at- yahoo -dot- com
I am having some trouble with the images used. They are loaded by the script asynchronously and sometimes, the script tries to use them before they are completely loaded, resulting in an exception. If you see a blank board, just refresh the page a few times until you see the board with some numbers already placed on it. And do let me know if you have some way of loading the images synchronously which works.
The 3D canvas is also not new and has been there since quite some time (Ajaxian article on Opera). The time when browser support for 3D matures enough to prompt some interesting applications is eagerly awaited.
