What is SVG?

SVG is the Abbreviation for Scalable Vector Graphics.

It is as the name implies a VECTOR based tool used for drawing 2D objects in HTML5.

SVG was developed by The World Wide Web Consortium(w3c) in 1999. Since then it has been the only HTML5 drawing tool which can still retain it's quality after being expanded or zoomed because it is vector based rather than pixel based.

One of the beautiful feature of SVG is the ability to make awesome and very easy animations with the tool, thus making it more preferable for 2D based animations to the pixel based HTML5 CANVAS.
Click Next to learn more.

SVG Elements

SVG has many number of Elements with which drawings and animations are easily made.

Heres a list of the most popular SVG elements

  • a
  • animate
  • animateMotion
  • animateTransform
  • audio
  • circle
  • clipPath
  • defs
  • desc
  • ellipse
  • fe(Filter Effects)
  • foreignObject
  • g
  • iframe
  • line
  • linearGradient
  • marker
  • mask
  • metadata
  • mpath
  • path
  • pattern
  • polygon
  • polyline
  • radialGradient
  • rect
  • script(JavaScript in SVG)
  • stop
  • style(CSS in SVG)
  • switch
  • symbol
  • text
  • textPath
  • tspan
  • use

Svg is fast, resolution independent and easy to learn.
Don't worry if you have never met any of the above listed elements before as I'm going to walk you through each one of them step by step.

Note: Some unsupported elements were excluded from the above list and some of the listed elements are not supported in Internet Explorer.

SVG Attributes

To start drawing on SVG, one has to open the SVG tag.


 ... 

Attributes
width
The svg width attribute is used to specify the width of your svg element.
height
The svg height attribute is used to specify the height of your svg element.
viewBox
This is the attribute which makes your svg drawings responsive.
It accepts four attributes "a, b, c, d".
a specifies a horizontal left padding for your svg element.

b specifies a vertical top padding for your svg element.

c,d gives a usable height to your svg element irrespective of its actual height.

If the viewBox is set. for each child element of the svg element, every input for the width and height is presented as a percentage of c and d respectively.

All you need is a basic understanding of HTML5 and you're good to go!

CHALLENGE

Which one of the following is NOT an SVG attribute?

Shapes

Basic Shapes are those objects which can be easily made using predefined tools.

The below listed elements makes drawing basic shapes easier in SVG.

  • rect
  • circle
  • ellipse
  • line
  • polyline
  • polygon

Each one of the above elements have different uses, click next to learn more!

rect

The rect svg element is used to draw rectangles.

attributes
x
Used to specify the left padding of the <rect>
y
Used to specify the top padding of the <rect>
width and height
Used to specify the width and height of the <rect>

Now, to make a rectangle, we first need to open the SVG tag and set up all of it's default attributes if we want or leave it because the svg tag has no required attribute. Then inside of it, we open the <rect> ... </rect> tag and as well, set up its default 4 attributes making sure that the 2 required attributes width and height are properly set.

lets now make a square of sides 60px with the rect tag!



    x="5" y="5" width="60px" height="60px">
    


output

Try it out

Theres another attribute called fill, it specifies the background color of every svg element, we can easily change the fill of our square to green by just adding the following attribute inside our rect opening tag fill="green".
Note that since we did not specify any fill for our square, it took the default fill black.

You can make animations with the <rect> element

circle

The circle svg element is used to draw circles.

attributes
cx
Used to specify the x-axis central cordinate for the <circle>
cy
Used to specify the y-axis central cordinate for the <circle>
r
Used to specify the radius of the <circle>

Now, to make a green circle of radius 30px, we need to open the <circle> ... </circle> tag inside the svg tag just like we did on the rect.



    cx="35px" cy="35px" r="30px" fill="green">
    


output

Try it out

Note that the fill was set to green making our circle green.

Note that the cx and cy circle attributes are very different from the x and y rect attributes because they start padding from the circle's center instead of it's top/left.
when making a circle, always make sure that these two attributes are greater than the radius attribute if you want all the circle to appear.
Here the two attributes are of lenght 35px giving our circle a left/top padding of (cx/cy - r=5px) padding.
just play with these two attributes to learn more!

ellipse

The ellipse svg element is used to draw ellipses.

attributes
cx
Used to specify the x-axis central cordinate for the <ellipse>
cy
Used to specify the y-axis central cordinate for the <ellipse>
rx
Used to specify the horizontal radius of the <ellipse>
ry
Used to specify the vertical radius of the <ellipse>

Now to make a colorless ellipse of horizontal radius 30px and vertical radius 15px, open the <ellipse> ... </ellipse> tag inside the svg tag, set the fill to none, and then use the stroke attribute to color it's borders.



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


output

9

Try it out

Note that the stroke was set to green in other to make our ellipse's outline green since the default value of stroke is none.

You can also use the attribute stroke-width to change the size of the borders.
This is also applicable to other elements.

line

The line svg element is used to draw a straight line.

The <line> svg element doesn't accept the fill attribute since its just a line.

attributes
x1, y1
Specifies the begining x and y axis cordinate for the <line>
x2, y2
Specifies the end-point x and y axis cordinate for the <line>

making a line is very easy, just open the <line> ... </line> tag inside the svg tag, set up the stroke if you want your line to have another color other than the default black and also set a value to the stroke-width to get a width greater than the default 1px if you want.

The following code outputs a cross, as specified by its 4 attributes.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


output

Try it out

Note the use of stroke-width which made the lines much bolder and stroke-linecap which specifies how the end points will look like. The brown line ends as a butt while the blue one has a round ending.

Some attributes like: fill, stroke, stroke-width, stroke-linecap etc...; can also be specified using CSS since they fall into the category of Presentation Attributes.

polyline

The polyline svg element is used to draw straight lines which can combine with each others.

Polyline accepts the fill attribute since its cordinates can joins each other to form a zigzag shaped line but it cannot close up to make a whole objects.
The fill attribute automatically closes up the shape.

attributes
points
Used to specify a "space or comma" seperated list of numeric values which denotes the points of the line.
Each pair of value represents a new offset of an x,y-axis for the polyline.
The number of values should NOT be odd.

To use the polyline element, open the <polyline> ... </polyline> tag inside the svg tag, set up the stroke if you want your line(s) to have another color other than the default black and also set a value to the stroke-width to get a width greater than the default 1px if neccesary.

The following code outputs an orange triangle with green borders.


width="100%" height="120px">
    fill="orange" stroke="green" stroke-width="10" points="100 10, 10 100, 200 100, 100 10">
    


output

Try it out

The above example prooves that the polyline elememt can never close, Note that the starting and ending points were the same but the line was clearly not connected as shown by the top angle of the above triangle.

Note that the width and height attributes of the svg element was set in other to see all the drawings cos it's default values might be smaller on some devices.

polygon

The polygon svg element is used to draw polygons.

Polygon automatically close up all it's shape only if the shape has more than one pair of points else its treated just like a line.

attributes
points
Used to specify a "space or comma" seperated list of numeric values which denotes the points of the line.
Each pair of value represents a new offset of an x,y-axis for the polygon.
The number of values should NOT be odd.

To use the polygon element, open the <polygon> ... </polygon> tag.
This element and path is mostly used to draw stars, rhombuses, hexagons and any shape that consists of joined straight lines.

The following code outputs a black/default colored triangle with green borders.


width="100%" height="120px">
     stroke="green" stroke-width="10" points="100 10, 10 100, 200 100" stroke-width="10">
    


output

Try it out

Note how polygon automatically closed up the shape even though we didn't close the points as we did on the polyline element making it a more perfect drawing tool than the polyline.

If the fill was not set for this element, as long as the points are more than one pair, it automatically set the fill to black which clearly shows that its a closed object.

Glossary

Congrats for learning up to this point, I trust you can now efficiently draw circles, rectangles, triangles and lines on svg using the right element(s).
The upcoming path module will teach you how to even draw all these shapes and practically every 2D object of your choice.

What we've learned on this module
<rect>
Used to make a rectangle.
<circle>
Used to draw a circle.
<ellipse>
Used to draw an ellipse.
<line>
Used to draw line(s)
<polyline>
Used to draw complex lines
<polygon>
Used to make any shape with three or more sides.

Note that all these elements accepts the global attributes including the JavaScript events!

Theses elements cannot be nested but the ending tag can be excluded since only the opening tags contains the attributes.

If you want to make any of these elements void(remove ending tag), you must add the optional "/" just before the closing angle brace, failure to do so will make some browsers to skip the rendering of all other elements after your void element.

CHALLENGE

Which one of the following elements does not accept the fill attribute?

path

The path element is used to draw any 2D shape in HTML5, it's known as the strongest drawing tool in SVG.
With this tool one can draw from a single line to multiple number of complex objects.

The path SVG element has an attributes called d which stands for data, this attribute describes the path and it has many number of parameters with which drawings are made on the path element.

Using the path

To draw with the path element, you have to open up the path and set up the data
Eg: <path d=" ..parameters.." />.
and you're good to go!

The path accepts all the basic attributes Eg: fill, stroke, stroke-dasharray etc...

Heres a list of all the parameters of the d attribute.

  • M, m (MoveTo)
  • H, h (HorizontalLineTo)
  • V, v (VerticalLineTo)
  • L, l (LineTo)
  • A, a (ArcTo)
  • Q, q (QuadraticCurveTo)
  • C, c (BezierCurveTo)
  • Z, z (ClosePath)

Each one of them has a small cap partner which describes relative positioning while the Capital lettered denotes absolute points.

Note that you dont realy need to close the path with an ending tag.
Each one of the above parameters have different uses, click next to learn more!

M

The M "moveTo" parameter defines where to place the drawing pen.
It takes 2 arguments ("M x, y"), where x defines the x-axis cordinate while y defines the y-axis cordinate.
This parameter must come first before other parameters.

The below example shows a pen placed at the point (50, 50)


width="100%" height="100px">
    d="M 50 50"/>


output

The m small cap parameter represents relative point, if you change the d parameters to "M 50 50 m 50 50", the pen will be placed at the point (100, 100)=> 50+50=100 which clearly shows that the relative parameter starts where it's predecessor droped off the pen.

If the relative parameter came first, the point will still be (50, 50).

Note that the pen doesn't appear, its just for visual explanation.

H

H "HorizontalLineTo" parameter defines a horizontal line.
It takes 1 argument ("H x"), where x defines the lenght of the straight horizontal line.

The below code shows a Horizontal line of lenght 50, a different output can be generated by replacing the absolute H with relative h which will lead to a longer line of 100vectors because the line will start from (50, 50) which is its's predecesor's ending point other than the initial absolute H which starts from (0, 0)


width="100%" height="100px">
    stroke="black" d="M 50 50 H 100"/>


output

All the path parameters accepts a negative value which denotes backwards drawing.
The below code shows a -30 line from (50, 50).


width="100%" height="100px">
    stroke="black" d="M 50 50 h -30"/>


output

If H was used, the line would have been 20(50-30).

Once the path is closed either with Z or by accurately making the last point meet with the first one, the fill can then be succesfully applied.

V

V stands for "VerticalLineTo" and it defines a vertical line.
It takes 1 argument ("V y") which defines the lenght of the straight vertical line through the y axis.

The V parameter is just like H but the difference is that H operates on the x axis while V runs through the top and bottom.
The below code shows a typical example.



    x="5" y="5" width="60px" height="60px">
    


0

output

The path is the greatest drawing tool because it's different parameters can be concatenated to produce an excellent object.
Let's try it out by making a square with those ones we've learnt.



    x="5" y="5" width="60px" height="60px">
    


1

output

h 30 v 30 h -30 v -30

Note how the relative h and v parameters joined each other to make a perfect closed square of sides 30.

To apply fill(color) on the path, use the attribute fill or CSS.

Z

Z means "closePath" and it draws a straight line from the end to the begining of the line.
Z does not have any argument(s).

Once the path is closed with Z, the object will automatically get filled with a default black background color unless otherwise stated.

The relative z parameter does exactly the same function as the absolute Z.

L

L means "lineTo" and it defines a straight line.
It takes 2 argument ("L x, y") x defines the x-axis cordinate while y defines the y-axis cordinate of the end point of the line.

L can efficiently replace the functions of H and V in an svg drawing.

Now let us make a trapezium with L.



    x="5" y="5" width="60px" height="60px">
    


2

output

Try it out

Note that we used only the absolute L throught the drawing.

The main difference between (H, V) and L is that the former draws only horizontal and vertical lines but the later can make horizontal, vertical and also sloppy lines.

A

A means "arcTo" and it defines an arc.
It takes 7 parameters ("A rx, ry, x-axisRotation, large/small, sweep?, x, y").
The relative a defines relative positioning.

The parameters
rx
rx defines the horizontal radius.
ry
ry defines the vertical radius.
x-axisRotation
This parameter of the A command specifies the x-axis rotation for the arc.
large/small
This parameter defines which arc to draw out of the two arcs.
This parameter is like a boolean, and it accepts either 0 or 1 where 0 draws the smaller arc while 1 draws the bigger arc.
sweep?
sweep accepts either 0 or 1. when 0, the arc takes the anti-clockwise direction but a value of 1 takes a clockwise path.
x and y
x and y are the end points/destination of the arc.

examples



    x="5" y="5" width="60px" height="60px">
    


3

output

sweep?=1 sweep?=0

Try it out

play with these parameters to get familiar with the A command.

Note that x-axisRotation has no effect on Firefox Gecko 7.

Q

Q means "quadraticCurveTo" and it defines a quadratic curve.
It takes 4 parameters ("Q dx, dy, x, y") where dx and dy are the control points and x and y are the destination.
The relative q defines relative positioning.

The below example shows how a Q command with the following parameters (M 100 50 q 25 -40 50 0) is being read by the browser.

dx, dy (25, -40) x, y (50, 0) M (20, 50)
The "T" command

The command T stands for "smoothQuadraticCurveTo" and it is used to smoothly continue a Q curve.
It takes 2 parameters (x, y), T takes the reflection of the control point of the previous Q command(dx, dy) as it's (dx, dy) thus creating a smooth curve from Q(x, y) to (T x, y).

The below code shows how to make a quadratic curve.



    x="5" y="5" width="60px" height="60px">
    


4

output

Try it out

Note that T or relatively t must be precceded by a Q command else it draws a curve which looks just like a line.

The next page teaches you how to make smoother curves.
Click next to learn more.

C

C means "bezierCurveTo" and it defines a bezier curve.
It takes 6 parameters ("Q dx1 dy1, dx2 dy2, x y") where dx1 and dy1 are the starting point's control points while dx2 and dy2 are the destination's control points, x and y are the destination.
The relative c defines relative positioning.

The below example shows how a C command with the following parameters (M 100 100 C 50 60 250 60 200 100) is being read by the browser.

dx1, dy1 (50, 60) dx2, dy2(250, 60) M(100, 100) x, y(200, 100)

If you're familiar with drawing packages, you must have noticed that C acts just like the shape tool of corelDraw.

The "S" command

The command S stands for "smoothQuadraticCurveTo" and it is used to smoothly continue a C curve.
It takes 4 parameters (dx2 dy2, x y), S takes the reflection of the last control point of the precceding C command(dx2, dy2) as it's (dx1, dy1) thus creating a smooth curve from the reflection of C(dx2, dy2) to (S x, y).

The below code shows how to make a cubic bezier curve.



    x="5" y="5" width="60px" height="60px">
    


5

output

Try it out

Have you seen just how smooth the bezier curve looks with just few parameters.

Note that S or relatively s must be precceded only by a C command in other to produce a C curve else it makes a Q like curve.

The main difference between Q and C is that the previous has one control point while C has two control points which makes it a more perfect choice for drawing curves in svg.

Grossary

Try it out

The above like hand was made with relative path commands which makes it very easy to change it's position by carefully altering the cordinates of the first M command.

The below code shows how to make the above shape.



    x="5" y="5" width="60px" height="60px">
    


6

SVG is easy, with just few commands we were able to make a beautiful complex shape.

Try making shapes around you to widen your knowledge on the svg path.

On the path element, we learned that:

  1. M moves to a starting point for the drawing.
  2. H Draws a horizontal line.
  3. V Draws a vertical line.
  4. L Draws a free line.
  5. A Draws an arc.
  6. Q & T Draws a quadratic curve.
  7. C & S Draws a bezier curve.
  8. Z Closes the path.

If you find it hard to memorize all of these commands i recommend using an svg shape generating tool like Inkscape or Illustrator.

When making path drawings, i recommend using only the relative(small cap) commands so that changing the objects position can be easily done later.

CHALLENGE

The color attribute of the path element is used to color the path.

<text>

The text SVG element is used to make texts in svg, it takes 2 main parameters (x, y) which defines the horizontal and vertical padding respectively.

text accepts the fill, stroke and stroke-width attributes of svg elements.
To make a text, open the <text> ... </text> tag.



    x="5" y="5" width="60px" height="60px">
    


7

output

I'm an SVG text!

Try it out

The above text has a left padding of 20 and a top padding of 60.
Note that texts written inside an svg tag does not appear eg: <svg> I'm an SVG text! </svg> wont appear.

An important thing about the text element is that it can also be fitted to a path!

attributes

The text element has many number of attributes which makes it's drawing and animation easier.
Below is a list of some of the text elements.

x

x defines the left padding for the text element.


y

y defines the top padding for the text element.


stroke

stroke specifies the color of the borders of the text element.
Eg: stroke="white"


text-anchor

The text-anchor attribute is used to align the text with either start, middle or end.
See the below example. text-anchor="start" text-anchor="middle" text-anchor="end" The red line is a visual aid to the cordinates(x, y) of the text element.


textLength

This attribute lets you specify the width of the space into which the text will be drawn.
See the below example. textLength="200" textLength="150" textLength="100"


lengthAdjust

This attribute is used in line with the textLength to control how the text is stretched or compressed into the length given by the textLength.
It has 2 different parameters(spacing & spacingAndGlyphs).
Eg: lengthAdjust="spacing" lengthAdjust="spacingAndGlyphs" Both of them has a textLength of 120.
Notice how "spacingAndGlyphs" adjusted to the available textLength because it acts on the entire text unlike "spacing" which acts only on the spaces between the letters.


Other attributes includes: fill, stroke-width, stroke-dasharray etc...;

Note that the default value for lengthAdjust is "spacing" and length is very different from lenght.

tspan

The tspan <text> element is used to define a section of text in a text element.

When used inside a text element, <tspan> ... </tspan> can specify a different size, color, position, transformation etc... for the enclosed text(s).

code


    x="5" y="5" width="60px" height="60px">
    


8

output

I am up and red in color

The <tspan> element can be nested but <text> cannot be nested!

textPath

I'm fitted to a beautiful path!

Try it out

The textPath element is used to make an svg text fit to a custom path.

<textPath> has one required attribute called xlink:href, this attribute specifies which path to fit the text by means of id.

The following code generates the above textPath.



    x="5" y="5" width="60px" height="60px">
    


9

Notice that we don't need the x, y cordinates for the <text> element as the <path/> takes care of everything.

If the text overflows the given path, the overflown text is hidden by default.

Make sure that you identified your path so that xlink:href can link to it with CSS syntax.

CHALLENGE

What is the default value for the lengthAdjust attribute?

Some Elements

a

The <a> svg element is used to make hyperlinks in svg, it is similar to the HTML <a> tag.


audio

The <audio> element is used to play music on svg, it is similar to the HTML <audio> tag.


defs

<defs> is used to define an element so it could be easily referenced in the future.
Any element that is enclosed inside a <defs> ... </defs> can be dublicated with the use tag.


use

The <use> element copies nodes of drawings and paste them anywhere.


desc

The <desc> element is used to describe an element using just text so it could be easily read by some visual or aural programs.


foreignObject

The <foriegnObject> element is used to import an external object into svg be it image or iframe. It allows for inclusion of a foreign XML namespace which has its graphical content drawn by a different user agent.


iframe

The <iframe> svg element is used to embed a browsing context in svg, it's very similar to the html iframe.
The below code shows how to embed an iframe into svg.


metadata

The <metadata> element is used to add metadata to SVG content. Metadata is structured information about data. The contents of metadata elements should be elements from other XML namespaces such as RDF, FOAF, etc.


switch

The <switch> <SVG>element evaluates the requiredFeatures, requiredExtensions and systemLanguage attributes on its direct child elements in order, and then processes and renders the first child for which these attributes evaluate to true. All others will be bypassed and therefore not rendered. If the child element is a container element such as a <g>, then the entire subtree is either processed/rendered or bypassed/not rendered.


stop

The <stop> element is used to add color stops to SVG gradient elements, it is a child element to either the <linearGradient> or the <radialGradient> element.

The above listed elements will be used in the upcoming lessons.

g

The <g> element is used to group svg drawings so that it could be referenced as one element.
Transformations applied to the <g> element are performed on all of its child elements, and any of its attributes are inherited by its child element.

The code bellow shows how the group element was used to color multiple elements.



    cx="35px" cy="35px" r="30px" fill="green">
    


0 a grouped text!

Try it out

Note how g set the colors of the border and the background of its child elements including the <text> element.

The power of the <g> element is not limited to colors only but it can also perform awesome animations.
Lets say we drew a fan with four <rect> tags, a <circle> and a <polyline>

We can easily apply rotation to the grouped rectangles with <animateMotion>
Thus:

The <g> element can be nested.

symbol

The <symbol> element is used to define graphical template objects which can be instantiated by a <use> element.
It accepts the global attributes including viewBox and preserveAspectRatio.
The viewBox attribute is used to preserve the alignment and space taken up by the child element of the <symbol> element whenever the use tag changes it's width/height.

An example of the symbol element.



    cx="35px" cy="35px" r="30px" fill="green">
    


1

output

a symbolic text!

Try it out

In the above output, the use element was used twice with different width & height. The smaller group of elements is the <use> with the w/h of 100 while the bigger one has a w/h of 300 making it take much more space than the initial because of they common viewBox.

Note that the symbol element can only be drawn if a use element references it!

clipPath

The <clipPath> element is used to define a region of an object where painting can be applied.
It's referenced with the clip-path attribute.

Note that any parts of the drawing that lie outside of the region bounded by the active clipping path are not drawn.

The code below shows how a clipping <circle> was used to clip(paint) a <rect>.



    cx="35px" cy="35px" r="30px" fill="green">
    


2

output

Try it out

Notice how the rectangle was cut in all parts which does not touch the circle.

The light rectangle/circle shows the original shape of the rectangle/circle.

The <clipPath> element uses an element to paint another element as shown in the above example.

Note that we defined the <clipPath> with <defs>

marker

The <marker> element is used for placing re-usable graphical elements along the outline of an SVG shape.

It's commonly used to place arrowheads or polymarks on the end of a markable element.

markable elements
  • <line>
  • <path>
  • <polygon>
  • <polyline>

The marker element is referenced with marker property.

marker properties
  • marker-start
  • marker-mid
  • marker-end
  • marker-segment
  • marker-pattern
  • marker-position

attributes
viewBox
This attribute specifies a rectangle in user space that should be mapped to the bounds of the SVG viewport established by the given element, taking into account the preserveAspectRatio.

refX
The refX attributes defines the x-axis reference point of the marker.

refY
The refY attributes defines the x-axis reference point of the marker.

markerUnits
The markerUnits attribute defines the coordinate system for the attributes markerWidth, markerHeight and the contents of the marker.

markerWidth
The markerWidth attributes represent the x-axis size of the viewport into which the marker is to be fitted according to the viewBox

markerHeight
The markerHeight attributes represent the y-axis size of the viewport into which the marker is to be fitted according to the viewBox

orient
The orient attribute indicates how the marker is rotated.
It accepts either a value of auto or auto-start-reverse.

Example.



    cx="35px" cy="35px" r="30px" fill="green">
    


3

output

Try it out

Notice how the marker properties were used differently to position different markers on the arc.

Try applying markers on <line>, <polyline> etc... to help broaden your knowledge on the subject matter!

You cannot apply marker on any other element other than the markable elements

pattern

The <pattern> element is used to fill or stroke an object using a pre-defined graphic object which can be repeated at fixed intervals.

It has an attribute called patternUnits used to define the coordinate system for attributes x, y, width and height which has a value of either "userSpaceOnUse" or "objectBoundingBox".

Example.



    cx="35px" cy="35px" r="30px" fill="green">
    


4

output

Try it out

Notice how the path was tiled by the child element of pattern

The default value for the patternUnits attribute is "objectBoundingBox"

CHALLENGE

Click on each option and drag to the top to correctly complete the below code which clips a circle.

<circle

cx="50"

cy="50"

r="20"

="url(#myClip)"

/>

clip-path
clip-fill

linearGradient

The <linearGradient> svg element is used to define rectangular color stops which will latter be used to fill/stroke a graphical object.

The <stop> svg element is used as a child element of <linearGradient> to define color stops and offsets for each different color of the gradient.

Eg:



    cx="35px" cy="35px" r="30px" fill="green">
    


5

output

Try it out

The stop child element has an attribute called stop-offset which defines the starting point of the stop's color.

Note that the <linearGradient> element is never rendered directly unless its used on an element!

radialGradient

The <radialGradient> svg element is used to define circular/radial color stops which will latter be used to fill/stroke a graphical object.

The <stop> svg element is used as a child element of <radialGradient> to define color stops and offsets for each different color of the gradient.

Eg:



    cx="35px" cy="35px" r="30px" fill="green">
    


6

output

Try it out

The stop child element can be used from 0 to infinity number of times.

If the offset of the latter <stop> child element of the gradient is equal to that of it's predecessor, a sharp color transition is formed.

CDATA

CDATA Otherwise known as Character Data are used to escape blocks of text containing characters which would otherwise be recognized as markup in XHTML.

CDATA is normally used in svg as the parent element of the contents of the <style> and <script> element.

Since CDATA is an XML(Extensible Markup Language) thing, it's deprecated in HTML and is rendered as a comment which only display "]]>" as the output.

But it still works as a parent to an <svg> style/script element contents.

style

The <style> svg element is used to embed style informations in an svg element.

The following code shows how to include CSS internal styling to an svg Element.



    cx="35px" cy="35px" r="30px" fill="green">
    


7

output

Try it out

Note how CSS defined the presentation attributes

The svg <style> element is NOT supported in Internet Explorer phone.

script

The <script> svg element is used to embed internal scripting in an svg element.

The below code shows how to create an ellipse using pure JavaScript.



    cx="35px" cy="35px" r="30px" fill="green">
    


8

output

Try it out

Note the use of "getElementNS("svgNS_URI", "qualified name of the element to create")" where NS means NameSpace and svgNS_URI means the svg NameSpace Uniform Resource Identifier which specifies a link to the svg namespace to be used, in this case "http://www.w3.org/2000/svg".
If the namespace URI was not specified, JavaScript cannot create the Element.

Although the script and style elements are embeded in svg, they still has a global scope in the entire document.

CHALLENGE

creatElementNS is used to create an SVG Element?

Filter Effect

Filter effects are graphics operations that are applied to a given source graphic to produce a modified graphical result.

With FE, one can make a 3d like object on SVG.

filter Elements
  • feDistantLight
  • fePointLight
  • feSpotLight
  • feBlend
  • feColorMatrix
  • feFuncR
  • feFuncG
  • feFuncB
  • feFuncA
  • feComponentTransfer
  • feComposite
  • feConvolveMatrix
  • feDiffuseLighting
  • feDisplacementMap
  • feFlood
  • feGaussianBlur
  • feImage
  • feMerge
  • feMorphology
  • feOffset
  • feSpecularLighting
  • feTile
  • feTurbulence

The <filter> element is referenced by using the "filter" attribute on the target SVG element or via the CSS filter property.

Click Next to explore FE.

light source

The FE light source elements are used to add a light source to a target svg element.
They are child elements to the lighting filters(feDiffuseLighting and feSpecularLighting).

Here's a list of the light source elements.

  • feDistantLight
  • fePointLight
  • feSpotLight

feDistantLight

The <feDistantLight> filter Element is used to add a distant light source to a target svg element.

Attributes
azimut
The "azimut" attribute accepts a numeric value which specifies the angle for the light source on the XY plane (clockwise), in degrees from the x axis.If the attribute is not specified, then the effect is as if a value of 0 were specified.
elevation
The "elevation" attribute accepts a numeric value which specifies the angle for the light source from the XY plane towards the z axis, in degrees. Note the positive Z-axis points towards the viewer of the content.If the attribute is not specified, then the effect is as if a value of 0 were specified.

fePointLight

The <fePointLight> filter Element is used to add a pointed light source to a target svg element.

Attributes
x
This attribute specifies the x-axis location for the light source in the coordinate system.If the attribute is not specified, then the effect is as if a value of 0 were specified.
y
 
This attribute specifies the y-axis location for the light source in the coordinate system.If the attribute is not specified, then the effect is as if a value of 0 were specified.
z
This attribute specifies the z-axis location for the light source in the coordinate system.If the attribute is not specified, then the effect is as if a value of 0 were specified.

feSpotLight

The <feSpotLight> filter Element is used to add a light source from a spot to a target svg element.

Attributes
x
This attribute defines the x-axis location for the light source in the established coordinate system.If the attribute is not specified,q then the effect is as if a value of 0 were specified.
y
This attribute defines the y-axis location for the light source in the coordinate system.If the attribute is not specified, then the effect is as if a value of 0 were specified.
z
The z attribute defines the z-axis location for the light source in the coordinate system.If the attribute is not specified, then the effect is as if a value of 0 were specified.
pointsAtX
Defines the x-axis location in the coordinate system established by attribute primitiveUnits on the filter element of the point at which the light source is pointing.If the attribute is not specified, then the effect is as if a value of 0 were specified.
pointsAtY
Defines the y-axis location in the coordinate system established by attribute primitiveUnits on the filter element of the point at which the light source is pointing.If the attribute is not specified, then the effect is as if a value of 0 were specified.
pointsAtZ
Defines the z-axis location in the coordinate system established by attribute primitiveUnits on the filter element of the point at which the light source is pointing.If the attribute is not specified, then the effect is as if a value of 0 were specified.
limitingConeAngle
Defines a limiting cone which restricts the region where the light is projected. No light is projected outside the cone.
This attribute accepts a numeric value as degree.If no value is specified, then no limiting cone will be applied.

The light sources can be animated using svg.

feComposite

The feComposite filter element is used to combine the two input images pixel-wise in image space.
operators: over, in, atop, out, xor, arithmetic.

The first five operators(over,in,atop,out and xor) are from the porter-duff image compositing operators while the arithmetic operator can be computed.


porter-duff

The porter-duff image compositing algebra is used to equip an image with an alpha channel that determines on a per-pixel basis whether the image is there or not.
The alpha channel is of the range 0 .. 1, When the alpha channel is 1, the image is fully there, when it is 0, the image isn’t there at all, and when it is in between, the image is partially there.
This should not be confused with opacity since they are very different from each other.

The porter-duff operators are 12 in number:

  • src
  • atop
  • over
  • in
  • out
  • dest
  • destAtop
  • destOver
  • destIn
  • destOut
  • clear
  • xor

The below image shows the effect of each operator when used on the two images(Source, Dest).

A visual aid on the porter-duff operators

The Name porter-duff comes from it's authors: Thomas Porter and Tom Duff.


arithmetic

The arithmetic operation is used to combine the output from the <feDiffuseLighting> and <feSpecularLighting> filters with texture data.
The result is calculated with the following formula:
result=k1*i1*i2 + k2*i1 + k3*i2 + k4
where:i1 and i2 indicate the corresponding pixel channel values of the input image, which map to in and in2 respectively. k1, k2, k3 and k4 indicate the values of the attributes with the same name.

feComposite attributes
operator
Specifies the compositing operation that is to be performed.
values: over, in, out, atop, xor, arithmetic;
k1, k2, k3, k4
The numeric values from these attributes are used to compute the arithmetic composing operator and is only applicable if operator="arithmetic". If the attribute is not specified, the effect is as if a value of 0 were specified.
in
This attribute identifies the first input for the given filter primitive.
Values: SourceGraphic, SourceAlpha, BackgroundImage, BackgroundAlpha, FillPaint, StrokePaint;
in2
This attribute identifies the second input for the given filter primitive.
Values: SourceGraphic, SourceAlpha, BackgroundImage, BackgroundAlpha, FillPaint, StrokePaint;

The two input attributes are used inline with the result attribute of filter primitives.

All the above attributes are animatable in svg.

The default value for the operator attribute is over.

lighting filters

The lighting filters are used to add a lighting effect to svg images using the Alpha channel as a bump map.
They includes the feDiffuseLighting and the feSpecularLighting filter elements.

<feDiffuseLighting>

The feDiffuseLighting lighting filter lights an image using the alpha channel as a bump map.
The resulting image is an RGBA opaque image based on the light color with alpha=1.0 everywhere.
The lighting calculation follows the standard diffuse component of the Phong lighting model.
The resulting image depends on the light color, light position and surface geometry of the input bump map.
The light map produced by this filter primitive can be combined with a texture image using the multiply term of the arithmetic <feComposite> compositing method.

attributes
in
See feComposite attributes for details
surfaceScale
specifies the height of the surface.If the attribute is not specified, then the effect is as if a value of 1 were specified.
diffuseConstant
Specifies the diffuse constant in Phong lighting model. This accepts a non-negative number.If the attribute is not specified, then the effect is as if a value of 1 were specified.
kernelUnitLength
This attribute specifies the intended distance in current filter units. It accepts two values with the second being optional. The first number is the dx value. The second number is the dy value. If the dy value is not specified, it defaults to the same value as dx.
lighting-color
Specifies the lighting color. This attribute accepts only a color value.
result
See arithmetic for details.

Example of <feDiffuseLighting> lighting filter on <fePointLight> light source.



    cx="35px" cy="35px" r="30px" fill="green">
    


9

output

BeforeAfter

Try it out

The k1 and the diffuseConstant attributes specifies the width of the brighter colored part of the filter.

<feSpecularLighting>

The feSpecularLighting SVG filter primitive lights a source graphic using the alpha channel as a bump map. The resulting image is an RGBA image based on the light color. The lighting calculation follows the standard specular component of the Phong lighting model. The resulting image depends on the light color, light position and surface geometry of the input bump map. The result of the lighting calculation is added. The filter primitive assumes that the viewer is at infinity in the z direction.This filter primitive produces an image which contains the specular reflection part of the lighting calculation. Such a map is intended to be combined with a texture using the add term of the arithmetic feComposite method. Multiple light sources can be simulated by adding several of these light maps before applying it to the texture image.

attributes
result, in, in2, lighting-color, kernelUnitLenght, surfaceScale
See feDiffuseLighting for details.
specularConstant
Same as diffuseConstant


    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


0

output

Try it out

Note that the result is "specOut" here.

Each light source element has a different function on the lighting filters.

feBlend

The feBlend filter element is used to composite two objects together using commonly used imaging software blending modes. It performs a pixel-wise combination of two input images.

attributes
inputs
in and in2
mode
Specifies the image blending mode.
It accepts any one of these values: normal, multiply, screen, darken, lighten;
If this attribute is not specified, then the effect is as if a value of normal were specified.


    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


1

output

Try it out

The table below shows the blending effect produced on the different modes.

modenormalmultiplyscreendarkenlighten
output

The feBlend filter element can also be used on images.

feColorMatrix

The feColorMatrix filter element is used to color elements based on a transformation matrix.

Every pixel's color value (represented by an [R,G,B,A] vector) is matrix multiplied to create a new color.

attributes
in
See the previous explanations.
type
Specifies the type of matrix operation.
values: matrix, saturate, hueRotate, luminanceToAlpha
The keyword matrix indicates that a full 5x4 matrix of values will be provided. The other keywords represent convenience shortcuts to allow commonly used color operations to be performed without specifying a complete matrix. If attribute type is not specified, then the effect is as if a value of matrix were specified.
values
The contents of values depends on the value of attribute type

Using the <feColorMatrix> with type="matrix".



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


2

output

Try it out

The above matrix is the same thing as
R: 0 0 1 0 0
G: 1 0 1 0 1
B: 1 0 0 0 1
A: 1 0 1 1 0

If a fill was applied to the target element, feColorMatrix will override it.

The Color Functions

The Color Transfer Functions are those filter element used to specify the transfer functions for the four input channels.

These elements are the child elements of feComponentTransfer filter element.

color functions
  • feFuncR
  • feFuncG
  • feFuncB
  • feFuncA

feFuncR: Transfer function for the red component of the input graphic.
feFuncG: transfer function for the green component of the input graphic.
feFuncB: transfer function for the blue component of the input graphic.
feFuncA: transfer function for the alpha component of the input graphic.

attributes
type
Used to specify the type of component transfer function. The type attribute determines the Applicability of the other attributes.
Values: discrete, gamma, identity, linear, table;
If type=identity, no other attribute is required for the color function.
tableValues
Used to specify a list of numeric value(s) separated by white space and/or a comma, which define the lookup table.
If the attribute is not specified, then the transfer function defaults to identity.
Applicability: only when type="table".
intercept
Accepts a numeric value used to specify the intercept of the linear function.If the attribute is not specified, then the effect is as if a value of 0 were specified. Applicability: only when type="linear".
slope
Accepts a numeric value used to specify the slope of the linear function.If the attribute is not specified, then the effect is as if a value of 1 were specified. Applicability: only when type="linear".
amplitude
Accepts a numeric value used to specify the amplitude of the gamma function.If the attribute is not specified, then the effect is as if a value of 1 were specified. Applicability: only when type="gamma".
exponent
Accepts a numeric value used to specify the exponent of the gamma function.If the attribute is not specified, then the effect is as if a value of 1 were specified. Applicability: only when type="gamma".
offset
Accepts a numeric value used to specify the offset of the gamma function.If the attribute is not specified, then the effect is as if a value of 1 were specified. Applicability: only when type="gamma".

If more than one transfer function element of the same kind is specified, the last occurrence will be used.

The default value for type is identity.

feComponentTransfer

The feComponentTransfer filter primitive performs component-wise remapping of data using the color functions.
It allows operations like brightness adjustment, contrast adjustment, color balance or thresholding.

The feComponentTransfer is the parent element of the color functions.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


3

output

Before After

Try it out

Note that the fill was a <radialGradient>.

Since the feFuncA was not specified, it's value defaults to identity.

feConvolveMatrix

The feConvolveMatrix filter primitive is used to apply a matrix convolution filter effect.

A convolution combines pixels in the input image with neighboring pixels to produce a resulting image.

attributes
in
View the previous description.
order
Accepts a numeric value greater than 0 which specifies the number of cells in each dimension for the kernelMatrix.
The first number, orderX indicates the number of columns in the matrix. The second number, orderY indicates the number of rows in the matrix.The default value for order is 3.
kernelMatrix
Accepts a list of numeric integer values which is used to specify the kernel matrix for the convolution. Values are separated by space characters and/or a comma. The number of entries in the list must equal orderX multiplied by orderY.
The default number of values for this attribute is 9.
divisor
After applying the kernelMatrix to the input image to yield a number, that number is divided by divisor to yield the final destination color value. A divisor that is the sum of all the matrix values tends to have an evening effect on the overall color intensity of the result. It is an error to specify a divisor of zero. The default value is the sum of all values in kernelMatrix, with the exception that if the sum is zero, then the divisor is set to 1.
bias
After applying the kernelMatrix to the input image to yield a number and applying the divisor, the bias attribute is added to each component. One application of ‘bias’is when it is desirable to have .5 gray value be the zero response of the filter. The bias property shifts the range of the filter. This allows representation of values that would otherwise be clamped to 0 or 1.
This attribute accepts only a numeric value.
If bias is not specified, then the effect is as if a value of 0 were specified.
targetX
Determines the positioning in X of the convolution matrix relative to a given target pixel in the input image. The leftmost column of the matrix is column number zero. The value must be such that: 0 <=targetX < orderX. By default, the convolution matrix is centered in X over each pixel of the input image (i.e., targetX=floor (orderX / 2 )).
targetY
Determines the positioning in Y of the convolution matrix relative to a given target pixel in the input image. The topmost row of the matrix is row number zero.
edgeMode
Determines how to extend the input image as necessary with color values so that the matrix operations can be applied when the kernel is positioned at or near the edge of the input image.
values:
duplicate(indicates that the input image is extended along each of its borders as necessary by duplicating the color values at the given edge of the input image.)
wrap(indicates that the input image is extended by taking the color values from the opposite edge of the image..)
none(indicates that the input image is extended with pixel values of zero for R, G, B and A.)
If attribute edgeMode is not specified, then the effect is as if a value of duplicate were specified.
kernelUnitLength
View the previous explanation
preserveAlpha
Accepts a boolean(True/False) value which indicates whether the convolution will apply to all channels.
 A value of True Opposes, while False Proposes.
If preserveAlpha is not specified, then the effect is as if a value of false were specified.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


4

output

Before After

Try it out

The above example shows how the <feConvolveMatrix> filter primitive is used to achieve an embossing effect.

A wide variety of imaging operations can be achieved through convolutions, including blurring, edge detection, sharpening, embossing and beveling.

feDisplacementMap

The feDisplacementMap filter primitive uses the pixels values from the image from in2 to spatially displace the image from in.

attributes
scale
Accepts a numeric value used to specify the displacement scale factor. The amount is expressed in the coordinate system established by attribute primitiveUnits on the filter element.
When the value of this attribute is 0, this operation has no effect on the source image.
If the attribute is not specified, then the effect is as if a value of 0 were specified.
xChannelSelector
Accepts any one of the color values(R | G | B | A) which indicates which channel from in2 to use to displace the pixels in in along the x-axis.
The default value for this attribute is A
yChannelSelector
Accepts any one of the color values(R | G | B | A) which indicates which channel from in2 to use to displace the pixels in in along the y-axis.
The default value for this attribute is A

feDisplacementMap also accepts the input attributes(in, in2).

The <feDisplacementMap> filter primitive is always used in conjunction with a void filter element eg: <feTurbulence>.

feFlood

The feFlood filter primitive uses the pixels values from the image from in2 to spatially displace the image from in.

attributes
flood-color
This attribute indicates what color to use to flood the current filter primitive subregion.
values: currentColor, color;
Default flood-color value is black.
flood-opacity
The flood-opacity property defines the opacity value to use across the entire filter primitive subregion.
values: range[0 .. 1]
Default flood-opacity value is 1.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


5

output

Try it out

In the above example the <feFlood> filter was referenced on a use element, but it can also be used in conjunction with other filter elements.

All the above attributes of <feFlood> filter primitive can be animated!

feGaussianBlur

The feGaussianBlur filter primitive is used to perform a Gaussian blur on the input image.

attributes
stdDeviation
Accepts two numbers used to specify the standard deviation for the blur operation. If two numbers are provided, the first number represents a standard deviation value along the x-axis of the coordinate system established by attribute primitiveUnits on the filter element.
The second value represents a standard deviation in Y. If one number is provided, then that value is used for both X and Y.A negative value is an error and a value of zero disables the effect.
If stdDeviation is 0 in only one of X or Y, then the effect is that the blur is only applied in the direction that has a non-zero value.
If the attribute is not specified, then the effect is as if a value of 0 were specified.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


6

output

Before After

Try it out

feGaussianBlur also accepts the edgemode attribute.

The more the stdDeviation, the more the blur effect produced.

feImage

The feImage filter primitive is used to produces an image similar to the built-in image source SourceGraphic except that the graphic comes from an external source.

attributes
xlink:href
Accepts the url of the image.
If this attribute is not specified, no effect is produced.
preserveAspectRatio
Used to specify the aspect ratio of the referenced image.
Read about the preserveAspectRatio attribute here.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


7

output

Before After

Try it out

Note that the x, y, width and height of the <filter> element was set to serve as a viewBox for the preserveAspectRatio attribute.

The above image filled the available space without overflowing the rectangle because preserveAspectRatio was set to none.

feMerge

The feMerge filter primitive composites input image layers on top of each other using the over operator with Input1(corresponding to the first feMergeNode child element) on the bottom and the last specified input, InputN(corresponding to the last feMergeNode child element), on top.

Many effects produce a number of intermediate layers in order to create the final output image. This filter allows us to collapse those into a single image.
Although this could be done by using n-1 Composite-filters, it is more convenient to have this common operation available in this form, and offers the implementation some additional flexibility.

element
  • feMergeNode

Each feMerge element can have any number of feMergeNode subelements, each of which has an in attribute.

<feMergeNode> attributes
in
Specifies which input of the siblings of <feMerge< to use.

If the topmost image input is SourceGraphic and this feMerge is the last filter primitive in the filter, the implementation is encouraged to render the layers up to that point, and then render the SourceGraphic directly from its vector description on top.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


8

output

Before After

Try it out

The canonical implementation of feMerge is to render the entire effect into one RGBA layer, and then render the resulting layer on the output device.
In certain cases (in particular if the output device itself is a continuous tone device), and since merging is associative, it might be a sufficient approximation to evaluate the effect one layer at a time and render each layer individually onto the output device bottom to top.

An important thing to note on the above code was that <feMerge> dublicated the green rectangle and applied a Gaussian Blur onto the duplicate's Alpha Channel(in="SourceAlpha") instead of just bluring the original rectangle's Alpha Channel.

feMorphology

The feMorphology filter primitive is used to performs fattening or thinning of artwork. It is particularly useful for fattening or thinning an alpha channel.

attributes
in
The first input attribute.
operator
Used to specify whether to erode(i.e., thin) or dilate(fatten) the source graphic.
Value: erode, dilate;
The default value for the operator attribute is erode.
radius
Accepts two numbers used to specify the radius (or radii) for the operation.
If the two numbers are provided, the first number represents the x-axis radius while the second value represents the y-axis radius.
If one number is provided, then that value is used for both X and Y.
If no value is given, then no effect will be observed since the default value is 0.

Example



    cx="35px" cy="35px" rx="30px" ry="15px" fill="none" stroke="green">
    


9

output

Before After

Try it out

The dilation | erosion kernel is a rectangle with a width of 2*x-radius and a height of 2*y-radius.

Notice how the green rectangle has increased in size because the operator was used to dilate the <rect>'s SourceGraphic(The rectangle itself).

feOffset

The feOffset filter primitive is used to offset | translate the input image relative to its current position in the image space by the specified vector.

attributes
dx
Accepts a numeric value which specifies the amount to offset the input graphic along the x-axis.
The default value is 0.
dy
Accepts a numeric value which specifies the amount to offset the input graphic along the y-axis.
The default value is 0.

Example



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


0

output

Before After

Try it out

As you can see in the above output, <feOffset> was used to translate the object 12/12 from it's initial position.

The feOffset filter primitive is important for effects like drop shadows.

feTile

The feTile filter primitive is used to fill a target rectangle with a repeated, tiled pattern of an input image.

attributes
in
Used to define the input channel to apply the effect.
x
Accepts a numeric value which specifies the amount to bound the input graphic along the x-axis.
The default value is the images width.
y
Accepts a numeric value which specifies the amount to bound the input graphic along the y-axis.
The default value is the images height.

If the x | y attribute of <feTile> is greater than the image's width | height, the visible width will be imageWidth + (imageWidth - Value).

Example



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


1

output

Try it out

As you can see in the above output, the stand alone <feTile> element was used to tile the image using the viewBox of it's sibling(feOffset).

The above tiles can also be animated using SVG elements.

If the in attribute is specified for <feTile> other than <feOffset>, a single copy of the image will fill up the viewBox.

feTurbulence

The feTurbulence filter primitive is used to creates an image using the Perlin turbulence function.
It allows the synthesis of artificial textures like clouds or marble.

The resulting image will fill the entire filter primitive subregion for this filter.

attributes
type
 Indicates whether the filter primitive should perform a noise or turbulence function.
Values: fractalNoise | turbulence.
The default value for the type attribute is turbulence
baseFrequency
Accepts two numeric values used to specify the base frequency(frequencies) parameter(s) for the noise function.
If two numbers are provided, the first number represents a base frequency in the X direction and the second value represents a base frequency in the Y direction but if one number is provided, then that value is used for both X and Y.
A negative value for base frequency is an error.
If the attribute is not specified, then the effect is as if a value of 0 were specified.
numOctaves
Accepts an integer value used to specify the numOctaves parameter for the noise function.
If the attribute is not specified, then the effect is as if a value of 1 were specified.
seed
Accepts a numeric value used to specify the starting number for the pseudo random number generator.
If the attribute is not specified, then the effect is as if a value of 0 were specified.
stitchTiles
Used to specify whether or not to achieve smooth transitions(stitch) at the border of tiles which contain a turbulence function. Value: stitch | noStitch;
The default value for stitchTiles is noStitch.

If the stitchTiles attribute of <feTurbulence> is stitch, then stitch tiles will be applied to the border of tiles which contains the turbulence function, else noStitch will be applied.

Example



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


2

output

Before After

Try it out

It is possible to create bandwidth-limited noise by synthesizing only one octave.

Note the use of <feDisplacementMap> in the above code.

The more the baseFrequency, the more the number of distortions produced.

CHALLENGE

Select all the "Light Sources" below.

SVG animations

One of the coolest feature of svg elements is they ability to be animated easily with the animation elements.

animation elements
  • animate
  • animateTransform
  • set
  • animateMotion

There's another animation element called <animateColor> previously used to animate the fill of an element but it's use is deprecated since <set> and <animate> can handle color based animations.

animation attributes
xlink:href
The xlink:href attribute is used to identify the element which is to be animated by means of id.
If this attribute is not specified, the element to be animated will be the immediate parent element of the animation element.
attributeName
Used tospecify the name of the target attribute of the element to apply the animation.
attributeType
Used to specify the namespace in which the target attribute and its associated values are defined.
Values: CSS, XML, auto;
The values are case-sensitive and the default value is auto.
begin
Used to specify when the animation should begin.
This attribute accepts any one of the value lists.
end
Defines an end value for the animation that can constrain the active duration.
This attribute accepts any one of the value lists.
min
Used to specify the minimum value of the active duration.
Values: clock-value | mean;
max
Used to specify the maximum value of the active duration.
Values: clock-value | mean;
from
Specifies the starting value of the animation.
to
Specifies the ending value of the animation.
by
Specifies a relative offset value for the animation.
dur
Accepts any one of the clock-values used to specify the duration of the animation.
repeatCount
Specifies the number of iterations of the animation function.
Values: numeric value, "indefinite"(The animation will repeat forever).
repeatDur
Specifies the total duration for repeat.
Values: value lists, indefinite(default).
fill
Specifies the position of the element after the animation.
Values: freeze, remove;
The default value for the fill attribute is remove.
calcMode
Specifies the interpolation mode for the animation.
This can take any of the following values: discrete, linear, paced, spline;
The default mode is 'linear', however if the attribute does not support linear interpolation (e.g. for strings), the calcMode attribute is ignored and discrete interpolation mode is used.
restart
Specifies how to restart the animation.
Values: always, whenNotActive, never;
The default value is always.
values
Specifies a semi-colon seperated list of values for use on the keyTimes and keySplines attribute.
keyTimes
Accepts a semicolon-separated list of time values used to control the pacing of the animation.
Each time in the list corresponds to a value in the values attribute list, and defines when the value is used in the animation function.
Each time value in the keyTimes list is specified as a floating point value between 0 and 1 (inclusive), representing a proportional offset into the simple duration of the animation element.
For animations specified with a values list, the keyTimes attribute if specified must have exactly as many values as there are in the values attribute.
For from/to/by animations, the keyTimes attribute if specified must have two values.
keySplines
A set of Bézier control points associated with the keyTimes list, defining a cubic Bézier function that controls interval pacing.
The attribute value is a semicolon-separated list of control point descriptions.
Each control point description is a set of four values: x1 y1 x2 y2, describing the Bézier control points for one time segment. The keyTimes values that define the associated segment are the Bézier anchor points, and the keySplines values are the control points. Thus, there must be one fewer sets of control points than there are keyTimes.
Just like keyTimes, the values must all be in the range 0 to 1.
additive
Controls whether or not the animation is additive.
Values:
sum(Animation will add to the underlying value of the attribute and other lower priority animations).
replace(Animation will override the underlying value of the attribute and other lower priority animations).
The default value for additive is replace.
accumulate
Controls whether or not the animation is cumulative.
Values:
sum(Specifies that each repeat iteration after the first builds upon the last value of the previous iteration).
none(Specifies that repeat iterations are not cumulative).
The default value for accumulate is none.

SVG allows both attributes and properties to be animated. If a given attribute or property is inheritable by descendants, then animations on a parent element such as a g element has the effect of propagating the attribute or property animation values to descendant elements as the animation proceeds; thus, descendant elements can inherit animated attributes and properties from their ancestors.

value lists
clock-value
Clock values are values based on real time.
The following is the grammer for clock-value.
clock-val=Full-clock-val | Partial-clock-val | Timecount-val,
where:
Full-clock-val is of this format (Hours : Minutes : Seconds)
,Partial-clock-val is of this format (Minutes : Seconds)
,Timecount-val accepts a numeric value with any one of these suffix(es): "h" for hours, "min" for minutes, "s" for seconds, "ms" for milliseconds.
For Timecount values, the default metric suffix is "s" (for seconds).
The following are examples of legal clock values:
Full clock values: 01:02:03=1 hour, 2 minutes and 3 seconds.
Partial clock value: 01:02=1 minute and 3 seconds
Timecount values:
1h=1 hour
2min=2 minutes
3s=3 seconds
4ms=4 milliseconds
0.1234=123.4 milliseconds
offset-value
Accepts a clock-valueused to describe the element begin as an offset from the document begin.
Negative begin times are entirely valid and easy to compute, as long as there is a resolved document begin time.
Eg: offset-value="±5s".
syncbase-value
Describes a syncbase and an optional offset from that syncbase.
The element begin is defined relative to the begin or active end of another animation.
A syncbase consists of an ID reference to another animation element followed by either begin or end to identify whether to synchronize with the beginning or active end of the referenced animation element.
Eg: syncbase-value="begin ±3s".
event-value
Describes an event and an optional offset that determine the element begin.
The animation begin is defined relative to the time that the event is raised.
Eg: event-value="click ±2s".
repeat-value
Describes a qualified repeat event.
The element begin is defined relative to the time that the repeat event is raised with the specified iteration value.
Eg: repeat-value="repeat(4) ±6s".
accessKey-value
Describes an accessKey that determines the element begin.
The element begin is defined relative to the time that the accessKey character is input by the user.
Eg: accessKey-value="accessKey(K) ±3s". Once the "K" keyboard key is pressed, the animation will be fired.
wallclock-sync-value
Describes the element begin as a real-world clock time.
The wallclock time syntax is based upon syntax defined in Representation of dates and times [ISO8601].
Eg: wallclock-sync-value="wallclock(11:30:05 AM)".
indefinite
Specifies that the begin of the animation will be determined by a beginElement() method call or a hyperlink targeted to the element.

SVG's animation elements were developed in collaboration with the W3C Synchronized Multimedia (SYMM) Working Group, developers of the Synchronized Multimedia Integration Language (SMIL)

Only few of the svg elements cannot be animated.
An example of such element is the <defs>, <desc> etc.

<animate>

The animate SVG element is used to animate a single attribute or property over time.

This element accepts the animation attributes.

The following example shows how to make a path element change it's shape over time.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


3

output

Try it out

Note the path chosen by the animation and also notice that thei begin was set to 5s=with a full-clock-value.

You can as well set the begin access Key to any key that you want and the animation begin will be triggered once the key is pressed.
Note that accessKey is not supported in some browser versions.

<animateTransform>

The animateTransform SVG element animates a transformation attribute on a target element, thereby allowing animations to control translation, scaling, rotation and/or skewing.

This element accepts the animation attributes and the type attribute which is used to specify the type of transformation which is to have its values change over time. If the attribute is not specified, then the effect is as if a value of translate were specified.
The "type" attribute accepts any one of these values: translate | scale | rotate | skewX | skewY.

The following example shows how to make a scaling circle element.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


4

output

Try it out

The <animateTransform> animation element can also be used to rotate an svg drawing.
Thus:

The following example shows how to make a rotating line element.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


5

output

Try it out

In the above code, the type="rotate" has three parameters for the from and to which is read in this format( from|to="a b c" where: a=[rotation in degrees], b=[x-axis cordinate for the center of rotation], c=[y-axis cordinate for the center of rotation]).

Note that the small black <circle> was used to represent the center of rotation.

<set>

The set SVG element is usedfor setting the value of an attribute for a specified duration.
It supports all attribute types, including those that cannot reasonably be interpolated, such as string and boolean values.

This element is non-additive. The additive and accumulate attributes are not allowed, and will be ignored if specified.

The following example shows how to change the fill of a rectangle with <set>.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


6

output

Try it out

With <set> the fill immediately changes to red after 3s without being animated but with <animate> it will follow an opacity defined mode of animation.

The below example shows how the rectangle's fill changes by animating the opacity of each color value with <animate>.

As you can see in the above examples, the set element does'nt animate a property rather it changes/sets the value of a property overtime.

<animateMotion>

The animateMotion SVG element is used to move a referenced element along a motion path.

elements
  • mpath

The mpath element is used to define the motion path for the <animateMotion> element.
It accepts the xlink:href attribute used to reference the <path> to use.

This element is only applicable if the path attribute of <animateMotion> was not specified.

Consider the <path> and circle below:

We want the green circle to move along the path.

The below code shows how to achieve that with <animateMotion>.



    x1="100px" y1="5px" x2="100px" y2="100px" stroke="brown" stroke-width="12px" stroke-linecap="butt">
    
    
    x1="75px" y1="35px" x2="125px" y2="35px" stroke="blue" stroke-width="12px" stroke-linecap="round">
    


7

output

Try it out

In the above output, the cx and cy attributes of <circle> was defined by the cordinates of the <path> overtime.

Alternatively, the "path" attribute of <animateMotion> can also be used to directly define the motion path for the referenced element eg: <animateMotion path="M 20 20 L 60 60 ..."/>

If the "path" attribute is defined, then they will be no need for the <mpath> element.

CHALLENGE

Which one of the following is the recommended way to achieve a color based animations.

Take these few challenges let's know how much you've learnt!

View Result
Result
Round 1
Correct!
Wrong!

Your Answer
None
Round 2
Correct!
Wrong!

Your Answer
None
x
Home

Round 1

What is the full meaning of URI

Round 2

What is the name of the element that is used to perform fattening or thinning of artwork?

The End!

Currently we only have 2 challenges available but you can suggest more here so that i will manually add them up for you if it's fit!.

Round 1
Wait
Round 2
Correct!
Wrong
The End!
Correct!
Wrong
SVG Course By Nomeh Uchenna Gabriel SVG Course: Nomeh Uchenna Gabriel
Back
Home
Next
Click here to view options!
i
?
🔧
INFO
i

This SVG COURSE was made by Nomeh Uchenna Gabriel on Sololearn, It's intended to teach the most upto-date method of drawing with SVG .

The Course consists of: 8 Modules, more than 50 unique svg elements and an additional challenge Module where learners can test they skill by answering questions created by they fellow learners and also create they own quizzes.

The Modules also contains live results of code examples and a static code playground.

At the end of each module a challenge is given to the user based on the subject matter to help refresh his/her memory on the recently finished module.

Nomeh Uchenna Gabriel has participated in the editing of many SVG Docs on the web and mostly at MDN(Mozilla Documentation Reference)You're at the right place.

FAQ
?

What is this course all about?

This Course is intended to teach you how to create SVG web graphics/drawings.

How can i change the font size?

You can change the font size by going to setting(🔧)=> font size

How can i post comments and suggest quizzes?

You can post them here or at the comment section of this code

Why is it that whenever i copy something from this code it will display "Nomeh Uchenna Gabriel" instead of the copied text?

That is the architecture of the code, you don't have to worry about that.
Click on Try it out to view the code in action.

Why is there only 2 quizzes on the challenge module?

That's because you have not created a quiz, create one now.

Why can't i take the challenge over and over again after the first time?

That is the architecture of the code, which helps to make it simple and short, you don't have to worry about that.
Just rerun the code to take it again.

Why does some of the live code outputs fail to display

That's because you're on a browser which does not support the current code example.

Why isn't the animations on this code smooth?

That's because your "Mobile Data" is switched on, to view smooth animations, switch off your "Mobile Data".
Another potential cause is that you are on a device with a low RAM.

Why is some parts of the course hidden at the bottom

That's because you're using the web version of sololearn, the output is normal on the Mobile App.

SETTING
🔧

Font Size

A
A
A

Module Animations

Enable
Disable