Click here to Skip to main content
Click here to Skip to main content

Tagged as

Beginner's Guide to HTML5 & CSS3: Starting with SVG (Scalable Vector Graphics)

, 29 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Beginner's Guide to HTML5 & CSS3: Starting with SVG (Scalable Vector Graphics)

Introduction

Not a long ago, this image was making the rounds on internet and was getting as a popular joke among the developer community. It symbolized poor, homeless guy who was ready to 'code html for food' in return of help.

Fast forward 2007, the W3C accepted the HTML5 specification as the new for work for the HTML. Not only HTML5 gave a new overhaul to the web application landscape, it came almost at the right time when JavaScript was also getting more powerful and popular. Antwood's law which states that any application that can be written in JavaScript will eventually be written in JavaScript was also coming to reality.

Although HTML5 specifications are not yet final and various browsers have implemented their own versions of interpretations, we are seeing more standardization in web development. The web developers are more equipped with new tags and elements introduced. This article would particularly address one of the HTML5 standards known as Scalable Vector Graphics (SVG).

So, what is SVG?

The history of SVG goes well beyond HTML5. The first public draft specification of SVG was introduced by W3C in the year 1999. Its standards were based and derived from the experience of Precision Graphics Markup Language and Vector Markup Language.

Citing from the official spec at W3.org, SVG is described as: A language for describing two-dimensional graphics in XML. SVG allows for three types of graphic objects: vector graphic shapes (e.g., paths consisting of straight lines and curves), images and text.

Vector graphics are based on vectors (also called paths or strokes), which lead through locations called control points or nodes. On the other hand, raster graphics image, or bitmap, is a dot matrix data structure representing a generally rectangular grid of pixels, or points of color, viewable via a monitor, paper, or other display medium.

The most basic SVG file contains the following format:

  • Size of the viewport (Think of this as the image resolution)
  • Grouping instructions via the element — How should elements be grouped?
  • Drawing instructions using the shapes elements
  • Style specifications describing how each element should be drawn.

What are the advantages of using SVG?

  • SVG images can be embedded into the HTML document and rendered by the client browser, thus reducing the request traffic load.
  • SVG object can be animated when it uses the animation element or through JavaScript Library like jQuery.
  • The SVG images give you constant performance. It only deteriorates when the image resolution considerably increases.
  • SVG images can be printed with high quality at any resolution.
  • You don’t need an image editor to build SVG images. Because SVG is an XML based image format, you can practically use any text editor (my favorite is Notepad++).
  • You have full control over each element using the SVG DOM API in JavaScript.
  • SVG is an XML file format, which means that depending on each Web browser implementation the accessibility of SVG documents can be much better than that of canvas elements.

And how is it different from Canvas?

Developers often confuse the usage of SVG with another HTML5 feature called Canvas. While both of the can be sometime used to achieve the same functionality (see my earlier article on implementing Snake & Ladder game using canvas), one should consider a few points before deciding the tool for job.

With canvas, you don’t have any DOM nodes or elements to draw from. It’s all free format drawing on pixels. While in SVG you can implement animation and motion natively, that’s the not the case in canvas where you are on your own to implement animation using timer etc.

If accessibility is a concern, HTML might be better suited than SVG, being that it has more tools available for enabling and testing accessibility.

It should be noted that SVG itself might not be the best way to developer complex drawing in games and the best way to do that is take a mixed approach path of using SVG along with Canvas.

A brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips.

Time for some hands-on: Let’s build Snake & Ladder’s game

For starter’s Snake and Ladders in typical setting is dual player game and the object of the game is to navigate one’s game piece, according to die rolls, from the start (bottom square) to the finish (top square), helped or hindered by ladders and snakes respectively. Not to mention that having played this game so much in my childhood is one of the first thing I wanted to try out when I heard of HTML5 capabilities. I had attempted to have an implementation of this game using canvas earlier.

I started with an empty SVG tag in my html document.

<svg id="templateContainer">
</svg>

The SVG element indicates with in the HTML document that this section or element contains a SVG image and should be treated as. The typical attributes in SVG element are width and height which are used to specify its dimensions. I intentionally left them empty in the document html. However, they are being set at the document ready event using the jQuery.

$(document).ready(function() {

var dimension = $(window).height() - 100;

$("#templateContainer").height(dimension);
$("#templateContainer").width(dimension);

});

The above code should be very familiar to most of you and it does nothing more that setting the height and width attribute of the SVG element during the page ready event. This also indicates that you can simply treat it as any other element you would treat in HTML.

Next, I wanted to build a grid with 100 rectangles using the SVG. Of course, there are other ways using standard tables, div etc. to do this as well. Plus, I did not want to have static definition of 100 rectangle elements in my document. So, I defined a template SVG rectangle element as shown below:

<div class="row">
 <div class="col-md-8">
  <svg id="templateContainer">
   <rect x="0" y="0" width="0" height="0" class="orig">
   </rect>
  </svg>
 </div>
</div>

Later, I used a jQuery clone function to create 100 clones of the template rectangle and is assigned a different random class to create a fancy colorful grid.

function drawBoard() {  
  
 var squareSize = _winHeight / 10;
 
 var columnNr = 1; var leftToRight = true;
 var x = 0; var y = 0; var position = 100;
    for (var row = 1; row <= numerOfRows; row++)
    { 
  if (leftToRight)
        {
            x = 0;
        }
        else
        {
            x = $("#templateContainer").width() - squareSize;
        }
  
  for (var column = 1; column <= numerOfcolumns; column++)
        {
   rows[position - 1] = x.toString() + "," + y.toString();
   
   var clonedRect = $(".orig").clone(); 
   
   clonedRect.attr("x", x);
   clonedRect.attr("y", y);
   clonedRect.attr("width", squareSize);
   clonedRect.attr("height", squareSize);
   
   var rnd = Math.floor(Math.random() * 6) + 1;
   var className = "Rect Rect" + rnd.toString();
   
   clonedRect.attr("class", className); 
   clonedRect.appendTo( "#templateContainer" );

   var clonedText = $(".origText").clone(); 

   clonedText.text(position.toString());
   clonedText.attr("x", x + 30);
   clonedText.attr("y", y + 30);
   clonedText.attr("class", "text"); 
   clonedText.appendTo( "#templateContainer" );
   
   if (leftToRight)
   {
    x += squareSize;
   }
   else
   {
    x -= squareSize;
   } 
     
   position--;
  }  
  
  y += squareSize;
  
  leftToRight = !leftToRight;
 }
 
 $( ".orig" ).remove();
 $( ".origText" ).remove();
 
 drawLadders(); 
}

The width and height attributes of the element define the height and the width of the rectangle. You can use the style attribute is used to define CSS properties for the rectangle. Alternatively, you can use a CSS class to define the styling as shown in the above example.

The other predefined shapes you can have in SVG are:

  • Circle
  • Ellipse
  • Line
  • Polyline
  • Polygon
  • Path

In an ideal game, the snake and ladders are drawn. I decided to use the arrows pointing up and down to have the alternate for snakes and ladders. The red arrows represent snakes and white ones represent ladders.

<line x1="0" y1="0" x2="200" y2="200" class="origLine"/>    

The element is used to create a line. The x1 attribute defines the start of the line on the x-axis. The y1 attribute defines the start of the line on the y-axis. The x2 attribute defines the end of the line on the x-axis. The y2 attribute defines the end of the line on the y-axis.

The end of the line I decorated with the circles to show the direction. This is drawn using the circle element.

<circle cx="0" cy="0" r="8" stroke="white" stroke-width="3" fill="red" class="origCircle"/>

The circle element is an SVG basic shape, used to create circles based on a center point and a radius. The cx and cy attributes define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle's center is set to (0,0). The r attribute defines the radius of the circle

Demo

You can find a working demo of this implementation here:

Snake & Ladder Demo

Conclusion

SVG is powerful and necessary tool for any web developer these days considering the vastness of technological changes we have seen in the last few years. Not only it makes it easier to develop but at the same time opens the possibility for the areas which were not possible to implement on client side with this ease.

The Snake & Ladder game I have used for the demonstration in this article is by no means a symbol of best practice and should only be seen as a way to learn various available possibilities using SVG. In the meanwhile if you want to extend and take this idea further, please feel free and I would be glad to see that.

Thanks for spending your time to read this article and if you liked this please share with others.

By the way, did you know that there is this awesome website called CanIUse.com where you can check the compatibility of various desktop and mobile browsers for the various HTML5, CSS3, SVG features?

References and further reading

http://www.w3schools.com/SVG/svg_intro.asp

http://en.wikipedia.org/wiki/Jeff_Atwood

http://en.wikipedia.org/wiki/Scalable_Vector_Graphics

http://caniuse.com/svg

https://developer.mozilla.org/en/docs/Web/SVG

http://www.codeproject.com/Articles/262179/SVG-World-Map

http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html

http://dev.opera.com/articles/svg-or-canvas-choose

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Manas Bhardwaj
Architect
Netherlands Netherlands
Read my personal blog at www.manasbhardwaj.net.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 29 Apr 2014
Article Copyright 2014 by Manas Bhardwaj
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid