Mastering SVG
上QQ阅读APP看书,第一时间看更新

Gradients in SVG

As you continue to learn about basic SVG usage, I'm going to continue to tease new concepts in authoring SVG itself. The next features I'm going to introduce you to will be the definitions (defs) section, the gradient element, and the rect element.

The following example shows the source of the SVG element in the previous example. Everything beyond the root svg element itself is different to the previous example.

First up, there's the defs element. defs is an organizational element designed to hold definitions of graphical objects to be used later in the document. We immediately meet the linearGradient element, which defines (you guessed it!) a linear gradient. x1, x2, y1, and y2 define the gradient vector of the gradient. You'll learn more about that in Chapter 2, Working with SVG and CSS, but for now, just know that it defines the direction of the gradients. The default is 0 at the left and 1 to the right. Setting x2 to 0 and y2 to 1 changes the angle from a horizontal left-to-right gradient to a vertical top-to-bottom gradient. 

The look of the gradient is actually defined as child stop elements. Each has two attributes, offset and stop-color. The offset accepts either a percentage or a number between 0 and 1, representing the placement of the gradient stop on the totality of the gradient vector. This example is the simplest: one color at 0% and another at 100%. stop-color accepts any valid color value:

<svg width="10" height="40" viewBox="0 0 10 40" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="gradient" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#999999"/>
<stop offset="100%" stop-color="#000000"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="10" height="40" fill="url(#gradient)"/>
</svg>

As these are just instructions on how to render the gradient, it's possible to stretch and shift the background image in this case with zero loss of fidelity. The browser will just calculate new values and render a new, perfect gradient.

The following example shows a tweak to the CSS that stretches the header to be half of the height of the browser (using the vh unit) and forces the header background image to fill the available space (background: size: contain):

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mastering SVG- Using SVG images in CSS</title>
<style type="text/css">
.header {
color: #ffffff;
background: url(1-3-gradient.svg) repeat-x;
width: 500px;
height: 50vh;
text-align: center;
background-size: contain;
}
</style>
</head>
<body>
<div class="header"><h1>CSS!</h1></div>
</body>
</html>

As you can see in the following screenshot, the same background image handles the resizing with flying colors. This is true (as you'll learn) for anything else you can do with SVG.