SVG Basics – Coloring Objects in SVG
Coloring Objects in SVG
All SVG shapes have two attributes named ‘stroke’ and ‘fill’ which are used to paint them. The ‘stroke’ or border attribute determines the paint of the outside edge of the object while the ‘fill’ value determines the inner paint. These attributes need a paint value. A paint value includes colors and two “non-color” values you can use.
Stroke/Fill
|
Explanation
|
none
|
Nothing is shown. Painting with invisible ink!
|
currentColor
|
Results in the ‘color’ attribute being used to define the color. Included for compatibility with other non-SVG CSS documents (like HTML CSS). Some color requiring attributes include this.
|
Class
|
Explanation
|
Example
|
Keyword
|
SVG defines everything from ‘aliceblue’ to ‘yellowgreen’.
|
Aliceblue
|
Functional
|
A functional way to define the color. Either values in the range from 0 to 255 or percentages can be used. Mixing percents and values is illegal.
|
rgb(255,255,255)
rgb(100%,100%,100%) |
Hexadecimal
|
This is the same way colors are defined in HTML.
|
#FFFFFF
|
URI
|
A reference to a color gradient or pattern. Described later…
|
url(#MyGradient)
|
The difference between a paint and color in SVG is simply that paints can use the non-color values. Attributes needing a color can only use a value in ‘List 2’. In general, attributes needing a color end in ‘-color’.
Opacity effects the blending of colors being drawn to the screen and colors already there. Opacity can be applied to a group or an individual graphic element. Opacity is defined as a value from 0 to 1 or a percentage. A value of 1 or greater is opaque and no color shows from below. A value of 0 or less results in nothing being drawn. It is generally inherited and defaults to 1.
Attribute
|
Explanation
|
Applies to…
|
opacity
|
The overal opacity of the element.
|
Everything but gradient stops
|
fill-opacity
|
The opacity of the fill paint.
|
Elements with the attribute ‘fill’
|
stroke-opacity
|
The opacity of the stroke paint.
|
Elements with the attribute ‘stroke’
|
stop-opacity
|
The opacity of the gradient stop.
|
Gradient stops
|
A shape with ‘fill-opacity=”50%”‘ and ‘opacity=”50%”‘ is filled with color at 25% opacity.
If you need greater control of the opacity then use a gradient or a mask. Gradients can give you smooth transitions between opaque and transparent sections but they only apply to things you can stroke or fill. Masks give the greatest control as you can arbitrarily change the opacity of points on groups and individual elements.
Comments