Introduction to JavaScript Fall 2010 Class 9

esse quam videri
Jump to: navigation, search

Back to Introduction to JavaScript Fall 2010

Introduction

This week I will be talking about how you can generate interactive artwork with JavaScript. There are several ways to create graphics with JavaScript, but, this week, I will be focusing on a specific browser feature called SVG. I will show you how you can use the Raphaël library to easily generate interactive SVG graphics with JavaScript.

Graphics in JavaScript

Few Options

For most of JavaScript's history, there hasn't been a reliable way to use the language to draw images. There were various attempts in the past, but none of were supported across all browsers. For the most part, the best bet for creating artwork in the browser (without a plugin) was to use HTML, CSS and image tags to create the graphics you wanted, and then use a little bit of JavaScript to make those element dynamic. Basic HTML tags were sufficient for simple graphics, but browser plugins, mainly Adobe Flash, soon took over as the tool of choice for artists and designers looking to create browser based artwork.

SVG

In 1999, the W3C introduced a standard called Scalable Vector Graphics (SVG). SVG is an XML based format that can be used to define graphics. Just like HTML is used to specify data that gets turned into webpages, SVG is a format that gets turned into images.

SVG images are unlike other image formats that you're probably already familiar with. Instead of being bitmap images (like JPEG and GIF) that are set as one fixed size, SVG files define vector graphics images. Images that are created with vector graphics files are not set at any particular size. Instead, a vector graphics file defines a list of shapes that make up the image. Because of the way that these images are stored, vector graphics based images can be set to any size without degrading in quality. If you used Adobe Flash or Adobe Illustrator, you've used vector graphics, because both of these programs store their files in a vector graphics format (although, typically using a different format than SVG).

In the browser, SVG has another feature that other images formats don't have: you can use JavaScript to draw, resize, or animate the images. And just like you can add event handlers to HTML elements, you can add JavaScript event handlers to SVG elements as well.

Browser Support

As I said earlier, SVG was introduced in 1999. And then...nothing happened. At the time, Internet Explorer was the most popular browser and had already introduced a competitor to SVG called VML. Additionally, the Netscape browser was quickly losing ground in the browser wars, and adding support for SVG wasn't high on their list of priorities. So, despite being already being a standard, SVG simply wasn't used in the browser.

It wasn't until 2005, when Firefox added support for SVG documents, that using SVG in the browser actually became a realistic option. Today, all major browsers have at least some built in support for SVG. All browsers, except...you guessed it, Internet Explorer. There is hope though. The next version of Internet Explorer, version 9, is expected to have support for SVG built in.

Raphaël

As you've already seen with jQuery, JavaScript libraries can streamline the code you have to write to make your page dynamic. This week, I want to introduce you to another library called Raphaël. Like jQuery, Raphaël is a library that helps to streamline your code. However, instead of helping you write code to make your HTML dynamic, Raphaël helps you write code to make your SVG dynamic. As an added benefit, Raphaël uses some trickery to automatically bring many SVG features to current versions of Internet Explorer.

Creating the Canvas

Before you can start drawing with Raphaël you need to have a canvas to draw on. You can use the Raphael function to create a new canvas. There are several ways to create a new canvas, including creating a canvas inside of an HTML element. You can start simple by creating an empty canvas right on your page:

  var canvas = Raphael(0, 0, 800, 600);

The Raphael function takes in 4 parameters. The first two are x and y coordinates indicating the position where you'd like to create the canvas (in this example, it will be all the way in the top left corner). The second two parameters are for width and height and determine how large your canvas will be.

Creating an Element on the Canvas

Once you've created a new canvas, you can use canvas object to draw new elements. For example, you can create a new circle using the circle function:

  var circle = canvas.circle(50, 10, 60);

This creates a new circle located 50 pixels to right on the canvas and 10 pixels down. The circle will have radius of 60 pixels. Similarly, you can create rectangles and ellipses. Follow the links to each shape to see the Raphaël documentation for the element.

Changing an Element's Attributes

Just like jQuery, Raphaël gives you a function called attr that takes in an attributes object representing a collection of attributes you'd like to change for an element. However, instead of HTML attributes, Raphaël allows you to change SVG attributes. The Raphaël documentation provides a list of attributes that are commonly used. Some examples are below:

  // Create a new rectangle element
  var rect = canvas.rect(50, 50, 100, 100);
  
  // Change some attributes
  rect.attr({ width: 50, height: 50 }); // change the height and width
  rect.attr({ fill: '#5F93B1'}); // set an element's fill color
  rect.attr({ stroke: 'green' }); // set the stroke color for an element
  rect.attr(cx: 80, cy: 100); // move the element to position 80,100

Just like the attr function or the similar css function in jQuery will update an element's attributes immediately, the attr function in Raphaël will update an element's attributes immediately as well.

Animating an Element

If, instead of changing an element's attributes immediately, you'd like to animate an element instead, you can use Raphaël's animate function to animate an element to a set of attributes. Just like the attr function, the animate function takes in an object representing a collection of attributes you'd like to change. However, animate also takes in a second parameter, which specifies how long you'd like the animation to last:

  // Create a new rectangle element at position 0,0
  var rect = canvas.rect(0, 0, 100, 100);
  
  // Animate the element to position 50, 50 in half a second
  rect.animate({ cx: 50, cy: 50}, 500);

Raphaël's animate function is a little more flexible than jQuery's. Not only can you animate simple number values, but you can also animate some other attributes, such as fill and stroke colors.

You can also pass in another function as a callback to the animate function. So if it you'd like another function to run when animation is complete, you can pass it in as the 3rd parameter:

  rect.animate({ stroke: 'blue'}, 500, afterAnimate);
 
  function afterAnimate() {
    rect.animate({ fill: 'red' });
  }

The 3rd parameter is a callback function. Callbacks come in handy when you'd like multiple things to happen, but you need to wait for one function to be done before calling the next function.

Adding Events to Elements

Much like jQuery makes event handling for html elements a little bit easier, Raphaël gives you some functionality that makes event handling on SVG elements easier. In fact, the way that Raphaël allows you to add event handlers to SVG elements is almost identical to jQuery's method of adding event handlers to HTML elements:

  // On mouseover, change the size and color of the element
  rect.mouseover(handleMouseover);
 
  function handleMouseover() {
     this.animate({ height: 100, width: 100, fill: 'red' }, 200);
  }
 
  // On mouseout, shrink the element back down
  rect.mouseout(handleMouseout);
 
  function handleMouseout() {
     this.animate({ height: 50, width: 50, fill: 'blue' }, 200);
  }
 
  // On click, change the element's stroke color
  rect.click(handleClick);
 
  function handleClick() {
     this.attr({ stroke: "orange" });
  }

Chances are, if an event handler works in jQuery, it also works in Raphaël. This can come in handy for creating graphics that you'd like the user to be able to interact with.

Today's Interesting JavaScript Site

Activity 1

Follow along as I explain this Raphaël example.

Then take a look at the examples below to get any idea of what kinds of things you can do with Raphaël

Raphaël Examples

Activity 2

Download the template and we'll build a simple interactive SVG graphic.


Think About a Final Project

Look back over the content we've covered in this class and start thinking about a final project you'd like to do. Maybe you have a project for another class you'd like to use JavaScript for or a project at work that could be improved with JavaScript. Next week, I'd like you have some ideas for what you'd like to do for a final class project.