Using the HTML5 Canvas Element with the Google Web Toolkit (GWT)

Post to Twitter

With the release of the Google Web Toolkit 2.2 (GWT) they added experimental support for the HTML5 Canvas element. Looking over their sample application I was able to craft my own demo pretty easily borrowing some of their code and modifying it to suite my needs. I wanted to simplify their demo a little to expose just how easy it is to get started with the Canvas element in GWT. Today I’m going to build a simple GWT app that uses the HTML5 Canvas to draw some randomly placed and randomly colored boxes on the screen.

[ad name=”Google Adsense”]

Note: Keep in mind that the HTML5 Canvas support in GWT at this point in time is experimental which means this code might need to be modified in the future to work.

To get started I created a new GWT project called GWTCanvasDemo.

I removed all the sample source code from the project (remove all the greeting files and field validation file, etc.) and I modified the GWTCanvasDemo.html file to look like this:

<!doctype html>
<!-- The DOCTYPE declaration above will set the    -->
<!-- browser's rendering engine into               -->
<!-- "Standards Mode". Replacing this declaration  -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout.                        -->

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="GWTCanvasDemo.css">

    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title>Web Application Starter Project</title>
    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="gwtcanvasdemo/gwtcanvasdemo.nocache.js"></script>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->

    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.

I made one small addition to the GWTCanvasDemo.css file as follows:

.mainCanvas {
  border: solid 1px #000;
  margin-left: 20px;
  margin-top: 20px;

To implement the Canvas I modified the file as follows:

package com.giantflyingsaucer.client;


public class GWTCanvasDemo implements EntryPoint {
	Canvas canvas;
	Context2d context;
	static final int canvasHeight = 300;
	static final int canvasWidth = 300;
	public void onModuleLoad() {
		canvas = Canvas.createIfSupported();
		if (canvas == null) {
		      RootPanel.get().add(new Label("Sorry, your browser doesn't support the HTML5 Canvas element"));
	    canvas.setWidth(canvasWidth + "px");
	    canvas.setHeight(canvasHeight + "px");	    
	    context = canvas.getContext2d();
	    final Timer timer = new Timer() {	    	
	    	public void run() {
	  public void drawSomethingNew() {
		  // Get random coordinates and sizing
		  int rndX = Random.nextInt(canvasWidth);
		  int rndY = Random.nextInt(canvasHeight);		  
		  int rndWidth = Random.nextInt(canvasWidth);
		  int rndHeight = Random.nextInt(canvasHeight);
		  // Get a random color and alpha transparency
		  int rndRedColor = Random.nextInt(255);
		  int rndGreenColor = Random.nextInt(255);
		  int rndBlueColor = Random.nextInt(255);
		  double rndAlpha = Random.nextDouble();

		  CssColor randomColor = CssColor.make("rgba(" + rndRedColor + ", " + rndGreenColor + "," + rndBlueColor + ", " + rndAlpha + ")");
		  context.fillRect( rndX, rndY, rndWidth, rndHeight);

If you’ve read any of my previous articles on the Canvas element a lot of the code above won’t look to unfamiliar. The first thing is to check if the browser supports the Canvas element or not.

canvas = Canvas.createIfSupported();

If the browser doesn’t support the Canvas element I simply show a label (nothing fancy for this demo) stating the obvious. Here is the output in IE 7 (without any third party Canvas plug-ins):

At this point I set the height and width of the Canvas and attach it to the RootPanel. The next thing to do was grab the 2D context from the Canvas.

canvas.setWidth(canvasWidth + "px");

canvas.setHeight(canvasHeight + "px");	    

context = canvas.getContext2d();

Finally I setup a timer set to trigger every 1.5 seconds and to randomly draw a rectangle of random transparency, color and size by calling the drawSomethingNew method.

Hopefully I’ve kept the code as clear as possible and made this a simple example of how to get started with GWT’s new Canvas support. Again, keep in mind that as of the date of this article the Canvas support in GWT 2.2 is experimental.

Here is a screen capture when running the application:

Post to Twitter

This entry was posted in GWT, HTML5, Java. Bookmark the permalink.

7 Responses to Using the HTML5 Canvas Element with the Google Web Toolkit (GWT)

  1. Pingback: Daily for February 27th through March 2nd — Vinny Carpenter's blog

  2. Matko Klaić says:

    Tnx man! Gret job!

  3. Thanks for the tutorial. Just what I needed to get me started.

  4. Jai says:

    Awesome work mate. Hope to see many more tuts on this subject!

  5. Thomas says:

    I’m confused … The canvas incubator had a canvas emulation for IE which run out of the box without additional plugins.

    But the GWT canvas which moved now from incubator to main-line doesn’t have emulation?

    What happend with emulation?

    All the best,

  6. Rish says:

    Thanks for the info.
    Please also share that whether it is possible to create a node like structure using GWT Canvas .

    Refer :

    Please share can we create this using GWTCanvas or EXT or any advancd java technique

Comments are closed.