Jun 04 2008

Gwt-Ext Custom Reader

Tag: Ext, Gwt, Java, Javascript, Programming, WebAbhijeet Maharana @ 11:36 pm

Screenshot

If I had to populate a Gwt-Ext store with data in arbitrary format,

  1. I could parse data on the client and use a MemoryProxy + ArrayReader or

  2. I could have the server do the parsing and send JSON data to the client which could then be handled by a JsonReader for populating the store.

This thread at Gwt-Ext.com made me wonder if a good third option would be to have a reader that can be used directly with the store and proxy mechanism and that allows one to write parsing logic in Java on the client. I have attempted a CustomReader that does just that. You can use it with a proxy that fetches remote data.

CustomReader registers an Ext user extension of the same name. Ill refer to them as JavaCustomReader and JSCustomReader to avoid confusion. JavaCustomReader has a static method for registering the user extension.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
static {
	init();
}
...
private static native void init()/*-{
	$wnd.Ext.namespace("GwtExt");
 
        $wnd.GwtExt.CustomReader = function(meta, recordType, readerInstance) {
	      	meta = meta || {};
	       	this.readerInstance = readerInstance;
	        $wnd.GwtExt.CustomReader.superclass.constructor.call(this);
	};
 
	$wnd.Ext.extend($wnd.GwtExt.CustomReader, $wnd.Ext.data.DataReader, {
	      	read : function(response){
	       		return this.readerInstance.@com.maharana.gwtextcustomreader.client.CustomReader::read(Lcom/google/gwt/core/client/JavaScriptObject;)(response);
	        	},
 
        	readRecords : function(o){
			alert('Custom reader does not work with local data.');
        	}
        });
}-*/;

JSCustomReader is passed one additional parameter when it is instantiated. This parameter is a reference to the JavaCustomReader that created it.

1
2
3
protected native JavaScriptObject create(JavaScriptObject config, JavaScriptObject recordDef)/*-{
	return new $wnd.GwtExt.CustomReader(config, recordDef, this);
}-*/;

JSCustomReader’s read() method is called by a proxy which has finished loading remote data. The proxy expects a return object with the success status, total record count and actual records as its fields. JSCustomReader invokes JavaCustomReader.read() which looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public JavaScriptObject read(JavaScriptObject response) {
	ReaderResult r = handleRemoteResponse(new RemoteResponse(response));
	JavaScriptObject o = JavaScriptObjectHelper.createObject();
 
	JavaScriptObjectHelper.setAttribute(o, "success", r.success);
 
	JavaScriptObject[] jsRecords = new JavaScriptObject[r.records.length];
	for(int i =0; i<r.records.length;i++)
		jsRecords[i] = r.records[i].getJsObj();
 
	JavaScriptObjectHelper.setAttribute(o, "records", JavaScriptObjectHelper.convertToJavaScriptArray(jsRecords));
	JavaScriptObjectHelper.setAttribute(o, "totalRecords", r.records.length);
 
	return o;
}
 
// subclass and put your parsing logic here
public abstract ReaderResult handleRemoteResponse(RemoteResponse remoteResponse);

In turn, it handles the to/from JavaScriptObject stuff and calls handleRemoteResponse(). Users just need to provide their parsing code in this method in derived classes. RemoteResponse and ReaderResult are convenience classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class RemoteResponse {
	JavaScriptObject response;
 
	public RemoteResponse(JavaScriptObject response) {
		this.response = response;
	}
	public String getResponseText() {
		return JavaScriptObjectHelper.getAttribute(response, "responseText");
	}
	public String getResponseXML() {
		return JavaScriptObjectHelper.getAttribute(response, "responseXML");
	}
}
 
class ReaderResult {
	public final boolean success;
	public final Record[] records;
 
	public ReaderResult(boolean success, Record[] records) {
		this.success = success;
		this.records = records;
	}
}

This completes CustomReader. As an example, I made a simple CSV parsing reader as mentioned in that thread at Gwt-Ext.com. This reader gets stock quotes from Yahoo finance as a CSV file and creates records out of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
RecordDef recordDef = new RecordDef(  
	new FieldDef[]{  
        	new StringFieldDef("name"),
                new StringFieldDef("lasttrdate"),
                new StringFieldDef("lasttrval")
        }
); 
 
CustomReader c = new CustomReader(recordDef,1){
       	 public ReaderResult handleRemoteResponse(RemoteResponse remoteResponse) {
 
       		String csvalue = remoteResponse.getResponseText();
 
       		String[] lines = csvalue.split("\n");
       		Record[] records = new Record[lines.length];
 
       		for(int i=0; i<lines.length; ++i)
       		{
       			String[] columns = lines[i]. replace('\"', ' ').split(",");
       			records[i] = this.recordDef.createRecord(columns);
       		}
 
       		return new ReaderResult(true, records);
       	}
};

For getting the file from Yahoo, I made a utility Servlet Redirect.java which fetches the contents of a url and passes it to the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String queryString = request.getQueryString();
	String address = queryString.split("url=")[1];
	URL url = new URL(address);
 
	PrintStream out = new PrintStream(response.getOutputStream());
	String inputLine = "";
	BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
	while((inputLine = br.readLine()) != null)
	{
		// System.out.println(inputLine);
		out.println(inputLine);
	}
 
	out.close();
}

It is invoked by an HttpProxy on the client as follows:

1
2
3
4
5
6
...
String url = "http://download.finance.yahoo.com/d/quotes.csv?s=INFY+XOM+BBDb.TO+JNJ+MSFT+GOOG+YHOO&f=nd1l1";
DataProxy proxy = new HttpProxy("redirect?url=" + url);
 
Store store = new Store(proxy, c);	// CustomReader c from above
...

Once we have the utility servlet and CustomReader as part of the project, I think it will be relatively easier to populate stores with any arbitrary format data. Feel free to drop your comments / suggestions. I would love to hear them.

Download Eclipse project from Gwt-Ext.com or Rapidshare

Reference: GwtProxy by michal.bergmann


May 16 2008

Gwt-Ext and Number Madness

Tag: Ext, Gwt, Java, Javascript, Programming, WebAbhijeet Maharana @ 11:52 pm

Gwt-Ext Number Madness screenshotThis is the 3rd form of my game Number madness. I had first written it using TurboC during the vacation after junior college. And then as a Firefox extension. Both are available in the projects section.

Using Gwt-Ext for writing something like this sounds a bit silly. But it did make me learn something new: button templates; thanks to gwtext+ and sjivan. I have described the program below in brief. You can download Eclipse project from the link at the end of this post.

An Ext button is made up of a table with 3 columns. All three columns have parts of the button sprite as their background image and the center TD holds a <button> element. You can see this template in Button.java above the setTemplate() method definition:

1
2
3
4
5
6
7
8
9
10
<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap">
	<tbody>
		<tr>
	     		<td class="x-btn-left"><i>&#160;</i></td>
	     		<td class="x-btn-center">
	     			<em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td>
	     		<td class="x-btn-right"><i>&#160;</i></td>
	     	</tr>
	</tbody>
</table>

We can override this template to make the button look as we want it to. My modified template looks as shown below. There is only one extra CSS class for the table (see notes at end):

1
2
3
4
5
6
7
8
9
10
<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap mybutton">
	<tbody>
		<tr>
	     		<td class="x-btn-left"><i>&#160;</i></td>
	     		<td class="x-btn-center">
	     			<em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td>
	     		<td class="x-btn-right"><i>&#160;</i></td>
	     	</tr>
	</tbody>
</table>

This enables us to use CSS nesting to define x-btn-left, x-btn-center, x-btn-right and x-btn-text with the attributes we want while preventing the normal buttons from being affected. Thus we can use both Ext’s buttons and out custom buttons at the same time. I have defined them as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
.mybutton .x-btn-right {
	background: transparent url('button_right_06.png') no-repeat scroll right; 
	height: 150px;
	padding-right: 15px;
}
 
.mybutton .x-btn-left {
	background: transparent url('button_left_06.png') no-repeat scroll right; 
	height: 150px;
	padding-right: 15px;
}
 
.mybutton .x-btn-center {
	background: transparent url('button_06.png') repeat-x center; 
	height:150px;
	width:80px;
	text-align:center;
}
 
.mybutton .x-btn-text {
	line-height: 150px;
	font-family: Arial, Helvetica, sans-serif;
	font-size:60px;
	font-weight:bold;
}

I have used custom images that make up the button’s left, center and right components. I have also changed the appearance of the text displayed on the button.

Now that we have the buttons which make up the game board, lets take a brief look at the rest of the game. An integer array holds the numbers that map to each button on the board. This array is populated randomly at start. Although the board is 2D, I decided to use a 1D array as it turned out to be slightly simpler while populating the random numbers. So arr2D[i][j] becomes arr1D[i * numcols + j] where numcols is the number of columns in each row.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private void generateRandomNumbers()
{
	int i,j;
	int temp;
	boolean suitable;
	int total = numRows*numCols-1;
 
	for(i=0;i<=total;i++)
	{
		do
		{
			suitable = true;
			temp = (int) Math.round(Math.random() * total);
			for(j=0;j<i;j++)
			{
				if(numbers[j] == temp)
				{
					suitable = false;
					break;
				}
			}
		}while(!suitable);
 
		numbers[i] = temp;
	}
}

Once the array is ready, I set the Panel’s layout to TableLayout with 3 columns and call createGrid() to create buttons that make up the grid. Every button knows its (row,column) position and the blank square is made up of an invisible button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private void createGrid()
{
	for(int i=0; i<numRows; ++i)
	{
		for(int j=0; j<numCols; ++j)
		{
			int index = i*numCols + j;
 
			String label = String.valueOf(numbers[i*numCols + j]);
			final Button btn = new Button(label);
			btn.setTemplate(buttonTemplate);
 
			// listener is an instance of SquareListener
			btn.addListener(listener);
 
			// every button keeps track of its row and column number
			final int finali = i, finalj=j;
			btn.addListener("render", new Function(){
				public void execute() {
					JavaScriptObjectHelper.setAttribute(btn.getJsObj(), "row", finali);
					JavaScriptObjectHelper.setAttribute(btn.getJsObj(), "col", finalj);
				}
			});
 
			// empty square = invisible button
			// maintain a class-level reference to the empty square
			if (numbers[index] == 0)
			{
				emptyButton = btn;
				btn.setVisible(false);
			}
 
			add(btn);
		}
	}
}

The button listener checks if the clicked button is adjacent to the empty square. If it is, it swaps numbers in the array and on the buttons. The invisible button is now made visible and clicked button becomes invisible. I have added a fade in and fade out effect. However, this is shaky and sometimes the button doesn’t fade in for too long. It does irritate a bit. After this, the endgame is checked i.e. if numbers in the array are in ascending order.

I have left out some code to keep the post short. You can download the complete project from Gwt-Ext.com or Rapidshare.

Note:

  1. Since our new template just has an extra CSS class, the whole template thing could be avoided by calling btn.setCls(”mybutton”). This was an after-thought when I was done playing with the template.
  2. When you change the template, keep the <button> element otherwise you will get an exception at load time
    1
    2
    3
    4
    5
    
    [ERROR] Unable to load module entry point class com.maharana.gwtextnumbermadness.client.MainModule (see associated exception for details)
    com.google.gwt.core.client.JavaScriptException: JavaScript TypeError exception: btnEl has no properties
    	at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:481)
    	at com.google.gwt.dev.shell.ModuleSpace.invokeNativeHandle(ModuleSpace.java:225)
    	...
  3. Also keep the x-btn-center CSS class name otherwise you will get an exception when the button is clicked
    1
    2
    3
    4
    5
    
    [WARN] Exception thrown into JavaScript
    com.google.gwt.core.client.JavaScriptException: JavaScript TypeError exception: this.el.child("td.x-btn-center " + this.buttonSelector) has no properties
    	at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:481)
    	at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:270)
    	...

References:

  1. Images for new button template: http://www.jankoatwarpspeed.com/post/2008/04/30/make-fancy-buttons-using-css-sliding-doors-technique.aspx
  2. CSS nesting: http://webdesignfromscratch.com/css-inheritance-cascade.cfm
  3. Centering block level elements: http://dorward.me.uk/www/centre/#content

Do let me know if you have any corrections or suggestions.


May 01 2008

Gwt-Ext and Google Maps - II (handle click)

Tag: Ext, Gwt, Java, Javascript, Maps, Programming, WebAbhijeet Maharana @ 5:54 pm

Lat and Lon info being shown in a message box
This post is related to my earlier post on Gwt-Ext and Google Maps. While browsing the Gwt-Ext forum, I came across this thread with a simple-looking question from Martin: How can I get the LatLonPoint from a map when a user clicks on the map ??

I looked at the available methods to see if I could figure this out. When I realized I wasn’t getting anywhere, I tried looking at the source to figure out what was going on. I found that Mapstraction does have a facility to register callback functions for events. Below code snippets are from mapstraction.js.

1
2
3
4
5
6
7
8
9
10
11
Mapstraction.prototype.addEventListener = function(type, func) {
    var listener = new Array();
    listener.push(func);
    listener.push(type);
    this.eventListeners.push(listener);
    switch (this.api) {
    case 'openlayers':
        this.maps[this.api].events.register(type, this, func);
        break;
    }
}

When the callback functions registered for ‘click’ event are invoked, they are supplied with a LatLonPoint instance with the latitude and longitude information of the location which was clicked. See line 4 below.

1
2
3
4
5
6
7
Mapstraction.prototype.clickHandler = function(lat, lon, me) {
    for (var i = 0; i < this.eventListeners.length; i++) {
        if (this.eventListeners[i][1] == 'click') {
            this.eventListeners[i][0](new LatLonPoint(lat, lon));
        }
    }
}

However, this argument is lost because of the way Gwt-Ext API exposes this functionality: MapPanel class registers a function with no parameters. Below code snippet is from MapPanel.java. Note the native method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void addEventListener(final String event, final Function listener) {
	if (!mapRendered) {
		addListener(MAP_RENDERED_EVENT, new Function() {
			public void execute() {
				doAddEventListener(event, listener);
			}
		});
	} else {
		doAddEventListener(event, listener);
	}
}
 
private native void doAddEventListener(String event, Function listener) /*-{
        var map = this.@com.gwtext.client.widgets.map.MapPanel::mapJS;
        map.addEventListener(event, function() {
            listener.@com.gwtext.client.core.Function::execute()();
        });
}-*/;

The solution is to override these two methods. For that we need an interface with an execute() method that can accept arguments. I added an interface ‘OneArgFunction’ that does this. We need a proper fix for this so that we can handle more arguments. For now, a one-argument method will suffice.

1
2
3
4
5
package com.maharana.gwtextmaps.client;
 
public interface OneArgFunction {
	public void execute(com.google.gwt.core.client.JavaScriptObject arg);
}

In the overridden methods below, I register a function which accepts the LatLonPoint instance as parameter and hands it over to the execute() method for further processing. Then I invoke the overridden addEventListener() to register an event handler that places a new marker and centers the map on the clicked location. GoogleMap inherits from MapPanel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
mapPanel = new GoogleMap() {
	public void addEventListener(final String event, final OneArgFunction listener) {
		if (!this.isRendered()) {
			addListener(MAP_RENDERED_EVENT, new Function() {
				public void execute() {
					doAddEventListener(event, listener);
				}
			});
		} else {
			doAddEventListener(event, listener);
		}
	}
 
	private native void doAddEventListener(String event, OneArgFunction listener) /*-{
	      	var map = this.@com.gwtext.client.widgets.map.MapPanel::mapJS;
	      	map.addEventListener(event, function(llp) {
	            	listener.@com.maharana.gwtextmaps.client.OneArgFunction::execute(Lcom/google/gwt/core/client/JavaScriptObject;)(llp);
	      	});
	}-*/;
 
	// constructor - attach event listener
	{
		addEventListener("click", new OneArgFunction(){
			public void execute(JavaScriptObject arg) {
				LatLonPoint llp = new LatLonPoint(arg);
				mapPanel.setCenterAndZoom(llp, mapPanel.getZoom());
				mapPanel.addMarker(new Marker(llp));
				MessageBox.alert("Clicked Location", "Lat: " + llp.getLat() + "<br>Lon: " + llp.getLon());
			}
		});
	}
};

This does the trick. I am not using any Google Maps specific code here so it should work for other providers as well. Do let me know if I have missed something obvious or got something wrong.

I have modified the demo I posted in my earlier blog entry to include this. You can download it from Gwt-Ext.com or Rapidshare.


Mar 17 2008

Gwt-Ext screencasts for beginners

Tag: Ext, Gwt, Java, Javascript, Links, Linux, Maps, Programming, Ubuntu, WebAbhijeet Maharana @ 8:51 pm

I have started out with Gwt-Ext and thought I will record some screencasts. These are for beginners who may need a hand when they are starting out and are anxious to jump right into code. The screencasts have been recorded on Ubuntu Feisty with Eclipse Europa.

There are 3 screencasts in avi and ogg format.

  1. First screencast shows the installation of Gwt 1.4 and Cypal Studio for Gwt. Cypal Studio is an Eclipse plugin that automates most of the tasks associated with GWT like adding a module and adding a remote service. In the screencast, I create a Gwt project using this plugin.
  2. Second screencast shows how to add the ExtJS Javascript library (2.0) and Gwt-Ext Java library (2.0.1) to the project. In the screencast, I create a simple Ext form with some text fields and a button.
  3. Third screencast (added on March 22) shows how to send form data back to the server. In the screencast, I validate form fields using regular expressions / Ext Vtype, add a remote service and then save form data in an Oracle database using the remote service.

    You can read this post for installing Oracle 10g XE on Ubuntu Feisty.

All screencasts are hosted at Rapidshare. Sanjiv Jivan, the author of Gwt-Ext has offered to host them at gwt-ext.com. I think the files are quite big and I am not well-versed with audio/video formats and parameters. If you know any way to reduce file size while maintaining the quality of screencasts, do let me know.

Download screencasts from Rapidshare.
Download Eclipse projects shown in the screencasts from Gwt-Ext.com or Rapidshare.

Update:
Sanjiv has been kind to host them at http://www.gwt-ext.com/screencasts/.
I have also edited the gwt-ext wiki accordingly. (See comments)

Related links:
Google Web Toolkit
ExtJS Javascript library
Gwt-Ext
Cypal Studio for Gwt


Dec 04 2007

Lively Kernel and Documancer

Tag: Javascript, Links, Linux, Programming, WebAbhijeet Maharana @ 10:47 pm

Lively Kernel

From being used in web pages to add “some” interactivity to being used in a web based “kernel”, Javascript has come a long way. A team at SUN has developed a kernel that provides an execution environment for applications meant for the browser. From the Sun Labs Lively Kernel page, “The Sun Labs Lively Kernel is a new web programming environment developed at Sun Microsystems Laboratories. The Lively Kernel supports desktop-style applications with rich graphics and direct manipulation capabilities, but without the installation or upgrade hassles that conventional desktop applications have.” Written entirely in Javascript, the Lively Kernel emphasizes on treating Web applications as real applications and aims to build a platform using a minimum number of technologies. So its Javascript for most of the things.

It comes with the ‘Morphic’ graphic library which was originally written for the ‘Self’ system at Sun. From the same page, “Morphic is a user interface framework that supports composable graphical objects, along with the machinery required to display and animate these objects, handle user inputs, and manage underlying system resources such as displays, fonts and color maps. A key goal of Morphic is to make it easy to construct and edit interactive graphical objects, both by direct manipulation and from within programs.”

It even includes an IDE that allows JavaScript applications to be inspected and modified from within the system itself. It is currently supported on Safari 3.0.3 public beta release. Runs on Firefox but has a lot of related nasty bugs and locked my browser. IE support is yet to be added.

Screenshot (image is located at SUN’s site)

Related links:

Documancer

This is an invaluable tool in any programmer’s toolkit. It is a documentation browser which supports HTML, DevHelp, Info pages, Manual pages, remote WWW sites and pydoc. But the feature that got me hooked is the full-text search. Specially when it comes to HTML documentation such as those created with javadoc. Documentation for the Java APIs is also available in WinHelp and HTMLHelp formats which enable searching. But for other libraries which use javadoc to generate their documentation, it is a pain to search for something. Specially when you are new to the library. That is where this gem shines.

Its UI is based on Gecko, Mozilla’s HTML rendering engine and it presents documentation of all formats in the same way. It supports bookmarks as well. It is implemented in wxPython and is available for Unix and Windows. It comes with a nice installer which takes care of all dependencies.

Related links:

Apparently, there is another Gecko! (that sells clothes) which comes before the Mozilla page in a Google search for “gecko home page”.


Dec 02 2007

Javascript 3D tricks

Tag: Javascript, Programming, WebAbhijeet Maharana @ 9:27 pm

Opera 9.50 Alpha [Windows download ~ 5 MB] has added support for the 3D canvas. Tim Johansson, responsible for the Canvas and image decoding support in Opera has a blog entry on this. Firefox 3 Beta 1 [Download page] has an extension for this purpose and Vladimir’s blog entry on the same is located here.

I did a quick search for “javascript 3d graphics” to see if any libraries have sprung up for the calculations and other 3D chores. But I found some other neat stuff instead. ‘Neat’ not in the sense that they render some heavy-duty graphics in your browser but they use simple tricks to draw 3D objects. However, the authors may not agree with the “simple” part.

  1. JS3D:
    Renders 3D objects using plain text. The text is placed in DIV tags whose coordinates are calculated by 3D matrix operations. The objects can also be interactive. You have to see the demos to experience it. Specially the Double Helix demo.

  2. Triangles in Javascript:
    This one uses Javascript/DOM/CSS to render 3D triangles complete with lighting. And it achieves this by using plain old borders applied to DIV tags!

While they may not be suitable for writing games or other heavy graphics, but these nifty little tricks do impress a lot.


Nov 24 2007

Browser 2D canvas and Sudoku

Tag: Javascript, Programming, WebAbhijeet Maharana @ 9:14 pm

View script | Play 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:

Gradient filled circle drawn using the 2D canvas on Firefox 2

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.