password
username
Sponsored by CakeMail, an email marketing software.
Newsletter preview

Email not displaying correctly? View it in your browser.

Issue 205: September 3rd, 2008  Tips, Tricks, News and Reviews for Web Coders

Introduction

Kevin YankWith the possible exception of the Watchmen trailer, I don't remember a comic book ever stopping the web community in shock. The surprise unveiling of Google Chrome yesterday—in comic book form—did just that.

Google leaked news of the browser yesterday by releasing a comic book (by comics legend Scott McCloud) describing the design decisions that went into the new browser.

For users, Chrome is a brand new web browser with blazing fast load times and a minimalist interface, designed to highlight page content over (ironically) browser chrome. Customary browser features are tucked away behind clever user interface elements, most of which are easily discoverable as you need them.

For developers, Chrome uses the same WebKit rendering engine as Safari, but bundles its own screaming fast JavaScript engine, called V8. The browser's common ancestry with Safari will help to reduce the testing burden on developers of a whole new browser, but when testing is required, Chrome includes a DOM/CSS inspector, an HTTP profiler, and a JavaScript debugger.

A beta of Chrome is now available for Windows, with a Mac version under development. For more on Chrome, check out Josh Catone's preview on sitepoint.com.

Top

EXPAND YOUR BUSINESS WITH W3 MARKUP

Rely on us to get more projects completed each week! We provide:

  • Pixel-precise hand-coded Valid CSS & (X)HTML for any project
  • Theme or "skin" implementation into popular software like: WordPress, Drupal, Joomla, MovableType, Blogger, Pligg, Textpattern, Typo3, osCommerce, Shopify, X-Cart, SMC, even HTML Email templates, Server Side Includes
  • Same-day turnarounds and pricing discounts
  • Search engine friendly semantic coding
  • 100% cross-browser, cross-platform browser compatibility
  • Money back guarantee and 100% non-disclosure

Get started here »

Summary

Easy Vector Graphics with the Raphaël JavaScript Library

by Andrew Tetlaw

Raphaël is a small JavaScript library written by Dmitry Baranovskiy of Atlassian, that allows you to create and manipulate vector graphics in your web pages. It's amazingly simple to use and is cross-browser compatible; supporting Internet Explorer 6.0+, Safari 3.0+, Firefox 3.0+, and Opera 9.5+. Internally Raphaël uses VML in IE and SVG in the other browsers.

Now, demos involving circles and squares are fine, but I wanted to create an example that demonstrated a legitimate, practical use of vector graphics. So how about real-time statistics measurement? Here's a screenshot of my Current Sprocket Usage line graph that plots real-time "sprocket" usage levels. Best of all, it was a snap to make.

The HTML is simple; we just need a heading and container to hold our canvas -- a div element:

<h1>Current Sprocket Usage: 
    <span id="readout"></span></h1>
<div id="graph"></div>

To start we have to generate a new graphics canvas. I always like to place all my code within an object definition in order to create a separate namespace, so we'll start with the following code:

var SpGraph = {
  init : function(){
    SpGraph.graph = Raphael("graph", 400, 200);
    SpGraph.graph.rect(
        0, 0, 390, 110, 10
    ).attr("fill", "#000");
  }
}

window.onload = function () {
  SpGraph.init();
};

Using the window.onload event we call our SpGraph.init method. Within this method we create our canvas using Raphael("graph", 400, 200). The first argument is the ID of our container element, the other two represent width and height. We store the returned canvas object in our SpGraph.graph property. With the next line we create a rectangle and set some attributes:

SpGraph.graph.rect(
    0, 0, 390, 110, 10).attr("fill",
"#000");

The rect method allows us to draw a rectangle specifying the x coordinate, y coordinate, width, height, and optionally a corner radius. Notice that we've also chained a call to the attr method to set the fill color. All Raphaël graphic objects support the attr method and there's a range of attributes you can set. Raphaël supports chaining all its methods, which we will take advantage of soon. Our effort so far has resulted in this lovely black rectangle with rounded corners.

Now lets add stripes! To do this we add the following loop to the SpGraph.init method:

for(var x = 10; x < 110; x += 10) {
  var c = (x > 10) ? "#333" : "#f00";
  SpGraph.graph.path(
      {stroke: c}).moveTo(0, x).lineTo(390,x);
}

The loop executes 10 times drawing a line each time; a red line for the first one and a gray line for the others. The Raphaël path method initializes the path mode of drawing, returning a path object. It doesn't actually draw anything itself; you have to use the path object methods, which are chainable. The moveTo method moves the drawing cursor to the specified x and y coordinates and the lineTo method draws a line from the cursor point to the point specified. The result is the stripey background below:

Keep reading, we finish the code below.

Top

Focus only on your application with The Hosting Cloud™

Rackspace.comJust code it, load it and go. You don't ever have to think about the hardware, let alone scaling it. Our advanced clustered technology automatically scales to give you the capacity you need. You sit back and watch it grow with your business. Learn more!

For as little as $100/month, get:

  • Online tools to create unlimited sites, databases & email accounts
  • 24x7x365 live phone & chat support
  • 50 GB of storage, 500 GB of bandwidth & 10,000 compute cycles
For really big applications, only pay for the resources you use.

Take Mosso for a 30-day test-drive. If it's not all that we say it is, we'll put your money back in your hand. Ready to Go Mosso?

So now we have to draw the actual graph line. The vertical axis (represented by the stripes) is the percentage usage level. The horizontal axis will represent time in 10 pixel increments. In the real world each update of the graph would be obtained via an Ajax call, say every 5 seconds, but here I just create random values and update the graph every second. Once again, we use the path method to draw a 5 pixel wide line.

We initialise the path and store the reference to it in the SpGraph.path property like so:

SpGraph.path = SpGraph.graph.path({
    stroke: "#0f0",
    "stroke-width": 5, 
    "fill-opacity": 0
}).moveTo(20, 110);

Every update, we extend the line using the lineTo method like so:

SpGraph.path.lineTo(
    20+SpGraph.updates*10, 110-perf);

perf is a random value between 0 and 100. The SpGraph.updates property is a simple counter that allows us to control how many updates before the line is reset. The counter value is also used to plot the location of the line on the horizontal axis. After 35 updates the line is reset by removing it, using the SpGraph.path.remove method, and starting a new one.

So the whole script looks like this:

var SpGraph = {
  init : function(){
    SpGraph.graph = Raphael("graph", 400, 200);
    SpGraph.graph.rect(
        0, 0, 390, 110, 10).attr("fill", "#000");

    for(var x = 10; x < 110; x += 10) {
      var c = (x > 10) ? "#333" : "#f00";
      SpGraph.graph.path(
          {stroke: c}).moveTo(0, x).lineTo(390,x);
    }
    SpGraph.startPath();
    SpGraph.updateGraph();
  },
  startPath : function() {
    if(SpGraph.path) {
      SpGraph.path.remove();
    }
    SpGraph.path = SpGraph.graph.path({
        stroke: "#0f0",
        "stroke-width": 5, 
        "fill-opacity": 0
    }).moveTo(20, 110);
  },
  updateGraph : function() {
    if(SpGraph.updates++ < 36) {
      // imagine this value comes 
      // from an ajax request
      var perf = Math.floor(
          Math.random() * 100);
      SpGraph.path.lineTo(
          20+SpGraph.updates*10, 110-perf);
      document.getElementById(
          'readout').innerHTML = perf+'%';
    } else {
      SpGraph.updates = 0;
      SpGraph.startPath();
    }
    SpGraph.timer = setTimeout(
        "SpGraph.updateGraph();",1000);
  },
  updates : 0
}
window.onload = function () {
  SpGraph.init();
};

Don't forget to see it working in the demo. OK, so maybe a sprocket usage graph isn't exactly the legitimate, practical example I promised, but at least you got a look at what you can achieve with Raphaël with only a little effort. The documentation on the site isn't complete, but it's not too difficult to work out anyway. Why don't you have a go yourself? Quick, Simple, cross-browser compatible, vector graphics on the web has never been easier.

Read the blog entry:

Andrew Tetlaw JavaScript & CSS Blog: Stylish Scripting
by Andrew Tetlaw

Easy Vector Graphics with the Raphaël JavaScript Library

Top

You love your product, but does your customer? Use Morae to find out.

Morae is the premier software for understanding customer experiences and sharing those insights clearly and powerfully.

From usability testing to focus groups and beyond, Morae helps you transform designs and marketing to make things people love.

That's all for this issue -- thanks for reading! I'll see you in two weeks.

Kevin Yank
techtimes@sitepoint.com
Editor, The SitePoint Tech Times

Top

Latest Release

The Ultimate HTML Reference

Book

Tell me more..

Free Book Samples

Simply JavaScript
Simply Rails 2
Build Your Own Database Driven Website Using PHP & MySQL, 3rd Ed.
The PHP Anthology, 2nd Ed.

New Technical Articles

Interview with Jeff Veen, User Experience Guru

Josh CatoneJeff Veen is a high-profile author, speaker, and user experience consultant who has lead design teams at companies such as Adaptive Path and Google. Jeff took some time out to answer a few questions submitted by the SitePoint Forums community.

Full Story...

Learn Adobe AIR, Part 2: Build a Customer Management App

Akash MehtaPart 2 of Akash's Adobe AIR tutorials describes how to build a simple Customer Relationship Management (CRM) application. Take the quiz at the end and receive a free pocket guide: Adobe AIR For JavaScript Developers, courtesy of Adobe!

Full Story...

 Techy Forum Threads

 More Techy Blog Entries

News & Trends

Google Working on Browser: What About Mozilla?
50 comments
Target Settles Accessibility Lawsuit for $6 Million
53 comments
Would You Switch To IE8?
81 comments

Web Tech

Tagging is Not Just for Content
9 comments
Attending Drupalcon 2008 - Szeged, Hungary
Another 100 Free Adobe AIR Books: First In, Best Dressed!
1 comment

PHP

Rasmus Lerdorf: PHP Frameworks? Think Again.
27 comments

ColdFusion

All's Quiet on the CF Front...
1 comment

Help Your Friends Out

People you care about can benefit from the wealth of information on new and maturing technologies available on the Internet. Help them learn how to do it by forwarding them this issue of the Tech Times!

Send this to a friend
You are subscribed as : ralrusu@gmail.com

*** ralrusu@gmail.com from this list.

Mailing Address:
48 Cambridge St, Collingwood, VIC, 3066 AU
Phone: +61 3 9090 8200
© Copyright 2008 SitePoint. All rights reserved.