As an entertainment medium, the web requires a judicious use of special effects to catch and hold interest. In contrast to other media formats, however, the web is limited by bandwidth. If we can find ways to make interesting effects with less data sent over the wire, we all win.

In this article, I’m going to talk about techniques to do more with some simple SVG tricks. In the interest of brevity, I shall assume readers have a rudimentary knowledge of SVG, so I will not explain the more basic concepts.

At the same time, to keep the code more easily understandable, I’ll avoid various optimizations so that I don’t have to explain them. This means the code will at times be more verbose than necessary, but recognize the verbosity is in the service of clarity.

Z-indexing in SVG

The following snippet of SVG code represents a circle:

<circle  cx="50" cy="50" r="25" fill="#ff0000" />

As do these:

<circle  cx="50" cy="50" r="25" fill="#ffff00" />
<circle  cx="50" cy="50" r="25" fill="#ffffff" />

If you have the first two circles in an SVG, you will see a single yellow circle. If you have all three, you should see nothing — assuming the SVG they are in is white.

The reason for this is SVG’s z-indexing rules, which dictate that when any two graphical elements occupy the same space, the one represented later in the XML tree that the SVG is described by will be given a higher z-index. The white circle is at the same position as the yellow and covers it precisely.

The r attribute on each circle represents its radius. Thus, if you want to have layered circles where you can see the circles underneath, you might do so by increasing the radius, like so:

If you did not have the white circle, it would look like you had a yellow circle with a thick red border or stroke. The same principle applies to other graphical elements in SVG.

Let’s suppose we put the following rectangle in between the white and yellow circle.

<rect x="25" y="25" width="50" height="50" fill="#ff00ff" />

Notice the x and y are half the cx and cy of the circle — because circles are drawn from the center out, and rectangles are drawn from the top left. It will look like this:

And finally, I will put another rectangle in between our previous rectangle and the white circle and rotate it to make a simple star shape:

<rect x="25" y="25" width="50" height="50" fill="#ff00ff" transform = "rotate(45 50 50)"/>

The 50 values represent the center of the rectangle, which is, of course, the same value as the cx and cy of our circle.

I think at this point we have enough little areas to play with that we can see about making some interesting effects with animation.

#web-development #developer

Animation Tricks with SVG z-index
2.15 GEEK