SVG

2018-05-18

SVG 官方文档
文档2

一. 概述

SVG 意为可缩放矢量图形(Scalable Vector Graphics)。
SVG 是使用 XML 来描述二维图形和绘图程序的语言。

二. SVG 使用方法:

1
2
3
4
5
6
7
8
9
10
xmlns="http://www.w3.org/2000/svg" //可定义 SVG 命名空间
cx="100" //圆中心的 x 坐标
cy="50" //圆中心的 y 坐标
r="40" //半径
stroke="black" //显示形状的轮廓的颜色 (路径)
stroke-width="2" //轮廓设置为 2px 宽
fill="red" //填充红色

stroke-linecap="round" //设置刚开始的小圆环
stroke-dasharray="0,10000" //一个表示长度,一个表示间距
  1. 矩形

    1
    <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" />
  2. 1
    2
    3
    4
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="100" cy="50" r="40" stroke="black"
    stroke-width="2" fill="red"/>
    </svg>
  3. 直线

    1
    2
    3
    4
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <line x1="0" y1="0" x2="200" y2="200"
    style="stroke:rgb(255,0,0);stroke-width:2"/>
    </svg>
  4. 文本

    1
    2
    3
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <text x="0" y="15" fill="red">SVG</text>
    </svg>

四. SVG 实例:

参考链接

倒计时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG</title>
</head>
<body>
<style>
svg{
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.text{
text-anchor: middle;
dominant-baseline: middle;
}
</style>
<svg width="400" height="400">
<!-- 设置底色圆环 -->
<circle cx="200" cy="200" r="150" fill="none" stroke="grey" stroke-width="40"/>
<!-- 进度条 -->
<circle class="progress"
transform="rotate(-90,200,200)"
cx="200" cy="200" r="150"
fill="none" stroke="red"
stroke-width="40"
stroke-linecap="round"
stroke-dasharray="0,10000"
/>
<text class="text" x="200" y="200" fill="red" font-size="50"></text>
</svg>
<script>
var progressDom = document.querySelector(".progress"); //获取进度条 circle 对象
var textDom = document.querySelector(".text"); //文本对象
function rotateCircle (persent){
//获取 svg 圆形环的总长,通过获取半径长度算出总长
var circleLength = Math.floor(2 * Math.PI * parseFloat(progressDom.getAttribute("r")) );
//按照百分比,算出进度环的长度
var value = persent * circleLength/total;
//红色:RGB 255,0,0
//蓝色:RGB 0,191,255
var red = 255+parseInt((0-255)/100*persent);
var green = 0 + parseInt((191-0)/100*persent);
var blue = 0 + parseInt((255-0)/100*persent);
//设置 stroke-dasharray 和路径颜色
progressDom.setAttribute("stroke-dasharray", value + ",10000");
progressDom.setAttribute("stroke", `rgb(${red},${green},${blue}`);
//设置文本内容和颜色
textDom.innerHTML = persent+'%';
textDom.setAttribute("fill",`rgb(${red},${green},${blue})`);
}

let num = 0, total = 60;
setInterval(() => {
num ++ ;
if( num > total ){
num = 0
}
rotateCircle(num)
},100)
</script>
</body>
</html>