How To Use Canvas4Z

From Documentation
How To Use Canvas4Z

Simon Pai, Engineer, Potix Corporation
June 8, 2010
ZK 5.0.2, Canvas4Z 0.8.0

What's Canvas4Z

Canvas4Z is an experimental component that uses the power of HTML Canvas to draw various objects on any modern browser, including IE6.

Enlightened by John Scattergood's idea (from Zebra) to connect Canvas to Java 2D API, we've build this new prototype to expand ZK's reach on graphic functionality in the future.

What can be done with Canvas4Z

Before we even introduce what functions Canvas provides, let's see how we can play with it first.

  • Note that even though IE 8 does not natively supports Canvas, you can still play the demo with IE, except that the text drawing function is disabled.

How to use Canvas4Z

Add a Canvas in zul

Like a regular component, in your zul file you can have:

<canvas id="cvs" width="800px" height="500px" />
  • Note that Canvas is always childless.

Prepare Drawable objects

Then, on server side, you can prepare Drawable items like:

// A rectangle at (50,100) with width 200px, height 300px
Drawable rectangle = new Rectangle(50, 100, 200, 300);

// A triangle
Drawable path = new Path().moveTo(50,50).lineTo(100,70).lineTo(70,100).lineTo(50,50).closePath();

// A piece of text at (100, 100)
Drawable text = new Text("ZK Canvas", 100, 100);
  • The API of Rectangle and Path are similar to APIs of java.awt.geom.Rectangle2D and java.awt.geom.Path2D

Operate Drawables on Canvas

You can add, insert, remove, or replace them on Canvas:

Canvas cvs = getFellow("cvs");
cvs.add(1, text);
  • The API is almost identical to Java List API
  • Upon these actions, Canvas will show the changes by drawing/redrawing items on browser accordingly.

Operate Java 2D Shapes on Canvas

And why not just add some Java 2D Shapes directly into Canvas?

cvs.add(new Arc2D.Double(100, 100, 300, 300, 0, 270, Arc2D.PIE));
cvs.add(new RoundRectangle2D.Double(50, 50, 200, 400, 10, 10));

Set drawing attributes on Drawables

Prior to sending drawable items into Canvas, you can specify some drawing attributes on the items:

// sets colors

// sets color transparency

// rotates the shape by setting transformation
rectangle.setTransformation(0.87, 0.5, -0.5, 0.87, 0, 0);

// sets outline width

// sets shadow effect
rectangle.setShadowOffset(10, 10);

// add whatever you want...

  • Almost all attributes defined in HTML 5 Canvas spec are supported (as long as your browser supports it too).

Client side programming

You can do pretty much the same things on client side, too:

var cvs = jq('#cvs');

var rectangle = new zkforge.canvas.Rectangle(50, 50, 100, 100);




Canvas opens a door to graphics on browser for ZK. By using its server and client side API together you can build many interesting application. Next time we will explore how we built this Paint demo using the concept of client-server fusion.


Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.