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

Drawing with code

Before you learn about other basic implementations, it's worth taking a look at the previous screenshot in a little more depth. Instead of just being text like the first example (which, after all, you could have just done in HTML), it shows four circles diagonally arranged across the canvas. Let's take a look at the source of that image and learn our first visual element in SVG, the circle element.

The following code sample shows the circle in action. It also shows how simple changes in markup attribute values can create visually interesting patterns. In it there are five circle elements. These all take advantage of four new attributes. cx and cy represent the center x and center y coordinates of the element on a coordinate plane. r represents the radius of the circle. fill defines the color that will fill the circle. fill accepts any valid CSS color value (https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). In this case, we're using a red, green, blue, alpha (RGBA) value to fill this with variations on pure red. The first few values remain the same while the fourth value, the alpha, doubles every time from .125 to 1 (fully opaque). Similarly, cx, cy, and r double each time. This produces the pattern you saw earlier. This isn't the most elaborate SVG image, but it does show you how easy basic SVG elements are to use and understand: 

<?xml version="1.0" encoding="UTF-8"?>
<svg width="250" height="250" viewBox="0 0 250 250" version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="12.5" cy="12.5" r="6.25" fill="rgba(255,0,0,.125)">
</circle>
<circle cx="25" cy="25" r="12.5" fill="rgba(255,0,0,.25)">
</circle>
<circle cx="50" cy="50" r="25" fill="rgba(255,0,0,.5)"></circle>
<circle cx="100" cy="100" r="50" fill="rgba(255,0,0,.75)">
</circle>
<circle cx="200" cy="200" r="100" fill="rgba(255,0,0,1)">
</circle>
</svg>