1 简单形状
SVG标签包含一些基本的构图元素,包括矩形,圆形,椭圆形,线条,文字和路径等。
SVG使用的是基于像素的坐标系统,其中浏览器的左上角是原点(0,0)。x,y的正方向分别是右和下。
- 矩形。
x和y的指定左上角的坐标,width和height指定矩形的尺寸。例如:
<rect x="0" y="0" width="500" height="50"/>
- 圆。
cx和cy指定圆心的坐标,ŗ表示半径大小。例如:
<circle cx="250" cy="25" r="25"/>
- 椭圆。
cx和cy指定圆心坐标,rx和ry分别指定横半轴纵半轴长度,例如:
<ellipse cx="250" cy="25" rx="100" ry="25"/>
- 线。
用x1和Y1到指定线的一端的坐标,x2和y2指定的另一端的坐标。stroke指定描边让线是可见的。例如:
<line x1="0" y1="0" x2="500" y2="50" stroke="black"/>
- 文本。
x和y指定文本的位置。例如:
<text x="250" y="25">Easy-peasy</text>
可以给文本设置样式。例如:
<text x="250" y="155" font-family="sans-serif" font-size="25" fill="gray">Easy-peasy</text>
2 SVG的样式
SVG的默认样式没有描边,并且是黑色填充。可以使用下面列举的一些常见的SVG样式/属性来美化你的可视化作品:
样式/属性 | 含义 | 可能的值 |
---|---|---|
fill | 填充 | 颜色值 |
stroke | 描边 | 颜色值 |
stroke-width | 描边宽度 | 数字(通常以像素为单位) |
opacity | 不透明度 | 0.0(完全透明)和1.0(完全不透明)之间的数值 |
font-family | 字体 | text标签特有,CSS字体 |
font-size | 字体大小 | text标签特有,数字 |
text-anchor | 对齐方式 | text标签特有,left/center/right |
- 其中颜色可以被指定为:
- 命名的颜色
green
- 十六进制值
#3388aa
或#38A
- RGB值
RGB(10,150,20)
- RGB与Alpha透明
RGBA(10,150,20,0.5)
- 命名的颜色
3 源码
下面做了一些实验,读者朋友可以作为参考:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>testD3-6-SVG.html</title>
<script type="text/javascript" src="http://localhost:8080/spring/js/d3.js"></script>
<style type="text/css">
.pumpkin {
fill: yellow;
stroke: orange;
stroke-width: 5;
}
</style>
</head>
<body>
<script type="text/javascript"></script>
<svg width=500 height=960>
<rect x="0" y="0" width="500" height="50"/>
<ellipse cx="250" cy="225" rx="100" ry="25"/>
<line x1="0" y1="120" x2="500" y2="50" stroke="black"/>
<text x="250" y="155" font-family="sans-serif"
font-size="25" fill="gray">Easy-peasy</text>
<circle cx="25" cy="80" r="20"
fill="rgba(128, 0, 128, 0.75)"
stroke="rgba(0, 255, 0, 0.25)"
stroke-width="100"/>
<circle cx="75" cy="80" r="20"
fill="rgba(0, 255, 0, 0.75)"
stroke="rgba(0, 0, 255, 0.25)" stroke-width="10"/>
<circle cx="125" cy="80" r="20"
fill="rgba(255, 255, 0, 0.75)"
stroke="rgba(255, 0, 0, 0.25)" stroke-width="10"/>
<rect x="0" y="300" width="30" height="30" fill="purple"/>
<rect x="20" y="305" width="30" height="30" fill="blue"/>
<rect x="40" y="310" width="30" height="30" fill="green"/>
<rect x="60" y="315" width="30" height="30" fill="yellow"/>
<rect x="80" y="320" width="30" height="30" fill="red"/>
<circle cx="25" cy="425" r="22" class="pumpkin"/>
<circle cx="25" cy="525" r="20" fill="rgba(128, 0, 128, 1.0)"/>
<circle cx="50" cy="525" r="20" fill="rgba(0, 0, 255, 0.75)"/>
<circle cx="75" cy="525" r="20" fill="rgba(0, 255, 0, 0.5)"/>
<circle cx="100" cy="525" r="20" fill="rgba(255, 255, 0, 0.25)"/>
<circle cx="125" cy="525" r="20" fill="rgba(255, 0, 0, 0.1)"/>
<circle cx="25" cy="625" r="20" fill="purple"
stroke="green" stroke-width="10"
opacity="0.9"/>
<circle cx="65" cy="625" r="20" fill="green"
stroke="blue" stroke-width="10"
opacity="0.5"/>
<circle cx="105" cy="625" r="20" fill="yellow"
stroke="red" stroke-width="10"
opacity="0.1"/>
</svg>
</body>
</html>