Thursday, December 22, 2016

Understanding SVG coordinate systems with an example

Before we start learning the generation of data visualizations with d3.js, lets spend some time to understand what is SVG and how does the coordination system works.


What is SVG?
  • SVG stands for Scalable Vector Graphics.
  • SVG is used to create different shapes that can be used in HTML or independently as graphics.
  • Using SVG we can draw shapes like circle, rectangles, curved lines, animations etc.
  • The most important part about using SVG is that it is scalable.
  • If we scale images, they can become pixelated or too sharp.
  • In case of SVG, the graphics scale well therefore making it a good choice for graphs for screens with varying dimensions.
  • Let’s see some simple examples using SVG.

SVG coordinate system

Please check above image and try to understand the difference between regular coordinate system and SVG coordinate system. One very important thing to notice is the locatoin of 0,0 coordinate. In gerular system its always at bottom left corner but in SVG system its at top left corner.

Let's learn this in detail with an example.

  • Create an empty HTML document and keep adding SVG elements as mentioned below
  • Add SVG element and give it height and width
  • Add a rectangle giving it `x`, `y`, ` width ` ,`height` and `fill`
  • Add a circle giving it `r`, `cx`, `cy` and `fill`

Your code should look like below image.


Save it as .html file and run in your favourite browser. You should be able to see something similar as below image.


Important points to remember
  • x starts from left corner and goes to the right.
  • So x=10 means 10 pixels to the right of the left edge
  • And x=-10 will mean 10 pixels to the left of the left edge.
  • y starts from the top and goes downwards.
  • So y=10 means 10 pixels below the top edge
  • And y=-10 will mean 10 pixels above the top edge

If you have any doubts or any query related to above example please put your comments and I would love to resolve your queries. Next post will be a example of data visualization using D3.js.

Next > Learn simple line chart using d3.js

No comments:

Post a Comment