Apps

Raphael JavaScript library simplifies creating graphics

The Raphael JavaScript library delivers a simple-to-use framework for creating graphics. Tony Patton explains how to use the Raphael library and describes the various options that are available in it.

 

Adding flare to a Web page often requires thorough knowledge of a graphic package like Photoshop or another technology like Flash. However, a number of technologies exist to create graphics within a Web page. The Raphael JavaScript library takes advantage of these technologies to deliver a simple-to-use framework for creating graphics.

Using vector graphics

Mathematical equations are at the heart of vector graphics. These equations are used to generate shapes via vector graphics. These shapes include points, lines, curves, circles, and any geometric shapes imaginable.

Raphael utilizes vector graphics via SVG and VML as its base for creating graphics. This is an important aspect of the library since it means every graphic object created is a DOM object, so JavaScript event handlers may be attached to the objects. Furthermore, the objects may be modified later via the DOM.

Now that we have an idea of the technology of Raphael, let's take a closer look at using it.

Getting Raphael

Like most libraries, Raphael is freely available. The beauty of it is its simplicity; the download is comprised of a single JavaScript file. The Raphael Web site has two download options: the compressed file or the JavaScript source file. Once downloaded, place it on your Web server and include a reference to this file when you want to utilize Raphael functionality in an application. Currently, the library supports Firefox 3.0+, Safari 3.0+, Opera 9.5+, and Internet Explorer 6.0+.

Creating shapes

Using Raphael is as simple as placing one line in your page. The following SCRIPT element references the library installed on the Web server and makes the functionality available in the page:

<script src="raphael.js" mce_src="raphael.js" type="text/javascript" charset="utf-8"></script>

The complete path to the raphael.js depends on where it is placed on your Web server. The Raphael site includes this JavaScript snippet to create your first application that uses the library. You can place this in a script block on a Web page that includes a reference to the Raphael JavaScript file as the following sample demonstrates.

<html><head>

<title>Raphael Test</title>

<script src="raphael.js" mce_src="raphael.js" type="text/javascript" charset="utf-8"></script>

</head>

<body>

<script language="javascript" type="text/javascript">

var paper = Raphael(10, 50, 320, 200);

var circle = paper.circle(50, 40, 10);

circle.attr("fill", "#f00");

circle.attr("stroke", "#fff");

</script></body></html>

This is a simple example that offers a great demonstration of the power provided by Raphael. The first line creates the canvas for the graphics with the paper variable. It uses the Raphael function, which defines the canvas or area of the page used to work with the graphics. The first two parameters set the starting point for our canvas: 10, 50. The final two parameters define the width and height of the canvas.

The second line creates a geometric circle via the circle method of the previously created instance of Raphael. The circle has a center point of 50, 40 with a radius of 10. The third line sets the fill attribute of the circle to the color specified by the hexadecimal value (which in this case is red). The final line sets the stroke attribute of our circle to white. This stroke attribute is the line around the outer edge of the circle.

Now we can extend the previous example to include multiple shapes. The following example places a rectangle (with rounded corners) inside our previous circle and places two smaller circles within the rectangle.

<html><head>

<title>Raphael Test 2</title>

<script src="raphael.js" mce_src="raphael.js" type="text/javascript" charset="utf-8"></script>

</head>

<body>

<script language="javascript" type="text/javascript">

var paper = Raphael(1, 1, 400, 400);

var circle = paper.circle(150, 140, 110);

var rect = paper.rect(100, 100, 100, 70, 10);

var circle2 = paper.circle(120, 125, 10);

var circle3 = paper.circle(140, 150, 10);

rect.attr("fill","#000");

circle.attr("fill", "#f33");

circle2.attr("fill", "#fff");

circle3.attr("fill", "#fff");

circle.attr("stroke", "#fff");

c.attr("stroke","#f33");

circle2.attr("stroke", "#fff");

circle3.attr("stroke", "#fff");

</script></body></html>

The objects are placed on the canvas in the order they are created in the script. So, the larger circle appears first, followed by the rectangle. The rectangle is placed on top of the circle. The final two small white circles appear last -- on top of the rectangle.

Looking at the numerous options

In addition to the circle and rectangle shapes included in the example, the Raphael library has more functionality to work with these shapes as well as others. The following list provides a sampling of these options.

  • rotate: Allows you to rotate an element by a given degree.
  • scale: Allows you to scale an element by the given number of times.
  • toFront: Allows you to move a specific element to the front so that it appears on top of other elements.
  • ellipse: Creates an ellipse shape.
  • moveTo: Moves an element to another area of the canvas using coordinates passed to it.
  • image: Allows you to embed an image in a given area of the canvas.

A full overview of Raphael's various options can be found on the Raphael site's reference page.

Simplified graphics

The number of freely available JavaScript libraries is a bit overwhelming, but I was instantly intrigued by the Raphael library because of its simplicity in size and ability to create graphics. One simple download, and you are ready to use it in minutes. You are only limited by your imagination with the drawings that can be produced.

Do you think the Raphael library will prove useful in your current and upcoming projects? What other JavaScript libraries do you use on a regular basis? Share your thoughts with the Web Developer community.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

10 comments
Fredz
Fredz

Having trouble getting the HTML validator working. This is not strict HTML 4.01 code. Don't see the results yet. Help appreciated, this looks very interesting. Thanks

Tony Hopkinson
Tony Hopkinson

Another attack vector for script kiddies and more of my resources being used to do 'your' stuff. Another 'good' solution to the wrong problem.

Jaqui
Jaqui

another waste of time. go ahead, give me a website with a javascript created graphic, I'll not see it because javascript is not supported. clientside scripting is criminaal. [ javascript, flash, activex controls. ]

Justin James
Justin James

Very neat, thanks! As you know, I have a side interest in working with graphics. It's nice to see a library that makes it easier to work with them in a Web browser, which eliminates expensive trips back and forth to the server. J.Ja

rdcpro
rdcpro

This library opens a lot of possibilites for learning basic programming skils.

tcarnevale
tcarnevale

A marvelous utility! Makes incorporating custom graphics into a web page straightforward.

Justin James
Justin James

... I don't agree. The browsers are supporting SVG and VML directly in the code now, and one of the biggest items in HTML 5 is figuring out how to get them (and MathML) baked directly into the HTML spec. This isn't really doing things that shouldn't be done, unless you feel (and there are good reasons to think so) that HTML shouldn't be supporting SVG and VML to begin with. J.Ja

Tony Hopkinson
Tony Hopkinson

looked to me like a javscript add on, so you could put any allowable code in there. So I say yes you can draw on my browser real estate and it stuffs my credit card number in a cookie, at the same time. If I'm wrong fair enough, but I didn't see anyway of stopping it doing something that isn't drawing on my browser real estate.

Tony Hopkinson
Tony Hopkinson

Jacqui's camp on client side execution. I understand why it's chosen, I've made good use of it on occasion for internal applications where trust is not an issue in terms of source. My point was if you want the graphics on the page (perhaps it would be non functional without them), then you have to execute the script, and that's straight js and so could do anything that could do. Even FF with no script the granularity is the URL of the site. Even if we could get down to security by behaviour, there's still another fly in the ointment. If a provider had to pay me for my resources to run their code, it would be a LOT less popular. Anything that proliferates client side scripting is unwelcome in my book.

Justin James
Justin James

Yes, from the user's standpoint, I suppose you are correct. If you really wanted to, I suppose that you could look at the HTML source to get the URL to the script, bring it up, and see what it does. From the developer's standpoint, this is an item that you pull onto your server (and have the ability to inspect) and refer to it there, instead of trusting the script to stay on a 3rd party's server and never be changed to something naughty. At the end of the day... there will always be potential trust issues. When I give my email address and make up a password for, say, eBay, I have no guarantee that they are not storing my password in plain text, and then trying my email address/password history over at Amazon, Yahoo! Mail, and my bank. Not saying that eBay *would* do that, just saying that there is almost always trust issues, unless you follow a super-tight approach and use the Web in a nearly 100% "read-only" mode. J.Ja