Friday 27 February 2015

SVG with RaphaelJS - Creating Basic Shapes - Drawing Circles with RaphaelJS

Last week's post provided the ground work for this series. This week, we will delve into code. We are going to start by drawing a circle with RaphaelJS. Yes basic stuff but at the end of the day, when we start applying the concepts, it becomes really exciting.

In the last post, I listed 5 things you can do with a Raphael element. They are:
  1. Create a Raphael element
  2. Manipulate the style of the element
  3. Transform the element
  4. Perform animations on the element
  5. Add JavaScript events to the element
For the circle, we are going to only carry out all the above steps. So without much ado, let's get started.

Create a Raphael element

A circle can be drawn using the Paper.circle(x, y, r) method in RaphaelJS. Its parameters are x, y and radius. I must add that the coordinate system of computers uses the top left corner of the viewport. On a computer this is the location of the icon for a program.

For our first example, we want to create a circle of radius 50 at the center of our viewport is 500x500 px. The location of the circle is at 250 for both x and y.

So in our init.js file our code would look like this:


$(function(){ var paper = Raphael('container', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
});


And when we view the result in the browser, we will see a circle at the center of the grid. I have hosted this project on Dropbox although you can use GitHub to do the same but for the purposes of this series, I will host with Dropbox and use GitHub to allow you have a copy of the code.

You can view the result of the above code here.

So there you have it. We have a basic circle with no styling whatsoever. Next we can style it. From now on, I will only describe the output you should see. I expect that you will open the link to the hosted version of the code.

You can view the code for this example on GitHub. Download a copy of the code and unzip it. Next run the index.html in your browser. You should see the same output as the hosted version.

Manipulate the style of the element

The circle we have created has no styling whatsoever. We add styling to an element using the attr() method. In this section we will draw a circle with a red border of radius 10.

Our code looks like this:


$(function(){ var paper = Raphael('paper', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
// Style the circle
circle.attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
});

You can view the changed output on Dropbox or get the code from GitHub.

Transform the element

We have 3 type of transformations we can carry out on an element. We can:
  1. Translate an element
  2. Scale an element
  3. Rotate an element
Because we are dealing with a circle, I will skip rotation of an element. In order to transform an element, we use the transform method.

Its syntax is Element.transform([tstr]); Here, tstr is your transform string. The transform string has 4 commands. They are: t for translate, r for rotate, s for scale and m for matrix.

The capital form of the transfom strings T, S, R and M are the absolute values. Absolute means that they will not take previous transformation into account when dealing with an element.

Translating a Circle

For our circle, we shall move it to the right by 150 px. To illustrate this, I will use the clone() method to create a clone of the circle based on our original circle.

Our init.js now becomes:


$(function(){ var paper = Raphael('paper', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
// Outline the circle
circle.attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
// Create a clone of the circle
var circle_clone = circle.clone();
// Transform the clone
circle_clone.transform("T150, 0") .attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
});

You can view the output of this code here or get the code from GitHub.

You can see that the circle has shifted. I use the clone() function because it doesn't take any parameters all we do is clone the circle and apply our transformation to it. The clone() function is a neat way of creating an exact copy of an element in RaphaelJS.

Scaling a Circle

Here we will scale the original circle. All we need to is apply a transformation on the original circle. The letter used to do this is the S. I will increase the size of the circle by 2.

This is the code to do it:


$(function(){ var paper = Raphael('paper', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
// Outline the circle
circle.attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
// Create a clone of the circle
var circle_clone = circle.clone();
// Transform the clone
circle_clone.transform("T150, 0") .attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
// Increase the size of the circle
circle.transform("S2");
});

You can view the output of this here or get the code from GitHub.

Perform animations on the element

The animate method in RaphaelJS has the following syntax:

Element.animate({parameters for animation}, number of milliseconds for animation to run, easing, callback function);

Only the animation parameters and the number of milliseconds for the animation to run are necessary.

We are going to make the circle increase in size by 3 over a period of 3000 milliseconds or 3 seconds.

The code to do this is given below:


$(function(){ var paper = Raphael('container', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
// Outline the circle
circle.attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
/* Increase the circle to 3 times its size over 3 seconds */
circle.animate({
transform:"s3"
}, 3000);
});

You can view the output of this here or get the code from GitHub.

Add JavaScript events to the element

We are going to create a flashing light whenever we hover on the circle. The hover syntax is given below:

Element.hover(f_in, f_out, [icontext], [ocontext]);

f_in is the function that is called when we hover in
f_out is the function that is called when we hover out

We replace our animate code and we have the following init.js file:


$(function(){ var paper = Raphael('container', 500, 500);
// Draw a circle at the center of the viewport
var circle = paper.circle(250, 250, 50);
// Outline the circle
circle.attr({ 'stroke' : '#ff0000', 'stroke-width' : 10 });
/* Increase the circle to 3 times its size over 3 seconds */
circle.hover(function(){
this.animate({
fill: '#FFFFFF'
}, 300);
}, function(){
this.animate({
fill: '#ff0000'
}, 300);
});
});

You can view the output of this here or get the code from GitHub.

Conclusion

In this section we have covered how to work with circles in RaphaelJS. I have gone through basic examples showing how this works.

In the next section, we shall start working on ellipses.Thank you for joining me on this series of SVG with RaphaelJS and have a great new month in March.

How to Enable Mod Rewrite in WAMP


Mod Rewrite is an important feature in WAMP. Generally it allows the rules in your .htaccess file be obeyed by your server.

One case of this is in WordPress. One of the first things you must do when you install a new WordPress site is to edit your Permalinks.

Permalinks affect how links to the site will be viewed by visitors. The moment you change the Permalink structure of your WordPress installation, it automatically creates a .htaccess file in your root folder.

This .htaccess file rewrites all your pages from the default URL used by WordPress. If you happen to do local developement of WordPress (Which is highly recommended), you need to enable Mod Rewrite on you WAMP.

To do this, simply look at the above image. If you can't figure it out, then follow the following steps:
  1. Launch your WAMP
  2. Right click on the WAMP icon and go to Apache Modules
  3. Locate rewrite_module from your list of Apache Modules
  4. Click it to enable it
  5. Wait for your WAMP to restart itself
There you are done. It wasn't so hard was it?


Friday 20 February 2015

SVG with RaphaelJS - Creating Basic Shapes - Drawing Rectangles with RaphaelJS

SVG with RaphaelJS - RaphaelJS Elements

In the first part of this series. I introduced the RaphaelJS template that we would be using to write our programs. I recommend that you download and look through the source code for this template.

This week, I will be covering the ground work on RaphaelJS. The RaphaelJS library was created with an emphasis on browser compatibility. The framework follows the SVG W3C Recommendation, which is a set of standards that ensure images are completely scalable and without pixelation. In addition to the use of SVGs, RaphaelJS even reverts to the Vector Model Language (VML) if rendered in Internet Explorer browsers prior to IE9. Although VML is very rarely used today, the support for it does a great job of showing the attention to detail that the RaphaelJS team placed on this project when developing the library.

I emphasize this point because RaphaelJS made its mark by supporting IE6. Back in the day that was big. But with its market share reducing, IE6 has lost its dominance. That said in web development you can never discount the effect of old browsers on how your pages will render.

When creating interactive graphics with JavaScript we have 2 options. We either use canvas or SVG. Canvas allows us to use it in a 2D or 3D context however, SVG allows us use its elements as part of the DOM. This difference means that for things like games and visualizations, we would use canvas. However for applications that require interaction with the DOM like data visualizations, SVG is the preferred choice.

Although RaphaelJS is a library used to for the creation of SVGs, it was not built with a total focus on the representation of large datasets. In turn, the gRaphaël JavaScript library was created. Weighing in at a mere 10KB, gRaphaël has proven to be a worthy extension to RaphaelJS. Although it may have not been developed behind things like a force-driven algorithm, nor does it come pre-configured with any physics properties, gRaphaël is still a well respected library for reasons ranging from its cross-compatible SVG structure, to its ease of use. As long as it coincides with the task at hand, I believe that gRaphaël should always be looked at as a viable resource to complete a project.

When we go into charting, we shall look at gRaphaël. One alternative to gRaphaël is D3D3 is a great library that also generates its charts in SVG. However, it is designed purely for data visualization.

Drawing in RaphaelJS involves creating a drawing area and drawing the element within the drawing area. The drawing area is called the viewport. Like an artist using a canvas, the visible part of the browser is the region we call the viewport. I highlight this because it is possible to draw off screen and render later on the visible area.

In certain applications like Flash, this drawing area was called a stage. The area outside the stage was where you kept assets to be preloaded as the program ran. This made programs have run time efficiency once they were loaded. Flash was the premier application for creating vector graphics for the web. Sadly, it has been losing market share so you can safely ignore it as a tool for working with vector graphics.

The changing landscape of web development has shifted to favouring a web free from plugins so HTML5 is the new standard for doing a lot of things that used to be done using Flash. SVG is part of the HTML5 specification so by implication, it takes over from Flash.

There is a lot of argument about HTML5 being a Flash killer and I will not go into that here. But what when down was that an efficient tool took over from a less efficient one. The death knell on Flash was sounded by the late Steve Jobs when he refused to allow Flash on any iOS devices in 2007. Since that time Flash has been in trouble.

When drawing in RaphaelJS, you can draw on the body of the browser itself or you can draw using a page element like the div in the last example. I personally prefer drawing on a page element and writing my code in a separate text file.

RaphaelJS supports three fundamental types of graphics elements: shapes, images, and text. Once we create a RaphaelJS Paper Object in the browser, we add the elements to it.

It is important to emphasize that RaphaelJS allows you to work with SVG created from programs like Adobe Illustrator and InkScape. This ability means that you simply need to create your graphics in one of this programs and export it to the SVG format. Adobe Illustrator is a great program from Adobe while InkScape is an open source alternative that natively outputs its images as SVG.

Adobe hired the creator of RaphaelJS Dmitry Baranovskiy who is working on an alternative to RaphaelJS called Snap.svgRaphaelJS was designed to support old browsers. Snap.svg removes support for old browsers and makes a clean break with the past.

Snap.svg was created from the ground up by Dmitry Baranovskiy. It leverages on the lessons he has learned building RaphaelJS so it will be important in the years to come. For now, it is yet to get to version 1.0 so its not ready for prime time.

In the meantime, learn RaphaelJS. A look at the video of Snap.svg shows you that it bears similarities to RaphaelJS. Think of this like C and C++. Snap.svg is an advancement over RaphaelJS.

Once you have a file in SVG format, you can use an online program like ReadySetRaphael to reverse-engineer your SVG code into JavaScript. This will then allow you to develop the application using RaphaelJS.

Later in this series, we shall work with interactive maps. I will go through the process of creating an interactive SVG map of a country in Africa. For now just store the above information in your head.

Creating the Raphael Object

This series is about SVG with RaphaelJS. I apologize for bothering you with talk. The goal of this section of the series is to lay a theoretical foundation for what we will be doing. Now on to some code.

Once you have the library loaded in your index.html page, in your init.js file you place this command.

var paper = Raphael('container', 500, 500);

The first argument in the function Raphael() is the id of the HTML element inside of which you would like to start drawing things. In our case, our init.js file looks like this:


$(function(){ var paper = Raphael('container', 500, 500);
});

So 'container' is the id of our container. However in JavaScript when we write code, we declare a variable with var. A variable is a label that you attach to a value. Sometimes, the value changes, sometimes it doesn't. But the label will always stay the same so that you can reference it throughout your code.

The command var paper assigns the RaphaelJS object to the paper variable. This allows us work with paper in our code. This reference to the paper object means that we would use paper for manipulation of our vector graphics

From the above example, we can see that the width and height of paper is 500px. If you looked at default.css carefully, you would realize that all we are doing is repeating the grid across both x and y axes.

The RaphaelJS Paper Object is assigned to a variable called paper. Through out our code, we can either assign paper to a variable or we can use it by itself. Personally, I prefer to assign variables so that I can keep track of my program logic.

After you have your paper object, in order to work with Raphael elements, you must:
  1. Create a Raphael element
  2. Manipulate the style of the element
  3. Transform the element
  4. Perform animations on the element
  5. Add JavaScript events to the element
The kind of application you want to develop will determine how far down the line you go but you will have to take the first step of creating a Raphael element before you can use it.

We will go into this in the next post in this series.