SVG-绘制柱状统计图

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4   <meta charset="UTF-8">
 5   <title></title>
 6   <style>
 7     body {
 8       text-align: center;
 9     }
10     svg {
11       background: #f0f0f0;
12     }
13   </style>
14 </head>
15 <body>
16   <h3>SVG绘图——各阶段课程难度系数</h3>
17   <svg id="s1">
18     <!--所有的特效对象-->
19     <defs id="effectList">
20       <!--<linearGradient id="g0" x1="0" y1="0" x2="0" y2="100%">
21         <stop offset="0" stop-color="#f00"></stop>
22         <stop offset="100%" stop-color="#f00" stop-opacity="0"></stop>
23       </linearGradient>-->
24     </defs>
25     <!--坐标轴小组-->
26     <g stroke="#555" stroke-width="2">
27       <!--X轴-->
28       <line x1="50" y1="450" x2="650" y2="450"></line>
29       <line x1="630" y1="440" x2="650" y2="450"></line>
30       <line x1="630" y1="460" x2="650" y2="450"></line>
31       <!--Y轴-->
32       <line x1="50" y1="450" x2="50" y2="50"></line>
33       <line x1="40" y1="70" x2="50" y2="50"></line>
34       <line x1="60" y1="70" x2="50" y2="50"></line>
35     </g>
36   </svg>
37   <script>
38     var w = 600+100;
39     var h = 10*40+100;//难度值*40高度倍率+双倍PADDING
40     s1.setAttribute('width', w);
41     s1.setAttribute('height', h);
42 
43     var data = [
44       {label:'HTML', value:3},
45       {label:'CSS', value:5},
46       {label:'JS', value:7},
47       {label:'DOM', value:6},
48       {label:'jQuery', value:5.5},
49       {label:'AJAX', value:8},
50       {label:'HTML5', value:6}
51     ];
52     var colWidth = 600/(2*data.length+1);
53     for(var i=0; i<data.length; i++){
54       var d = data[i]; //遍历每个数据对象
55       var cw = colWidth;  //柱子的宽
56       var ch = d.value*40;  //柱子的高
57       var x = (2*i+1)*colWidth + 50;
58       var y = 500-50-ch;
59 
60       //动态添加渐变对象
61       var c = rc();  //渐变颜色
62       var html = `
63       <linearGradient id="g${i}" x1="0" y1="0" x2="0" y2="100%">
64         <stop offset="0" stop-color="${c}"></stop>
65         <stop offset="100%" stop-color="${c}" stop-opacity="0"></stop>
66       </linearGradient>
67       `;
68       effectList.innerHTML += html;
69 
70       //动态创建矩形
71       var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
72       rect.setAttribute('width', cw);
73       rect.setAttribute('height', ch);
74       rect.setAttribute('x', x);
75       rect.setAttribute('y', y);
76       rect.setAttribute('fill', `url(#g${i})`);
77       s1.appendChild(rect);
78     }
79 
80     //random color
81     function rc(){
82       var r = Math.floor(Math.random()*256);
83       var g = Math.floor(Math.random()*256);
84       var b = Math.floor(Math.random()*256);
85       return `rgb(${r}, ${g}, ${b})`;
86     }
87   </script>
88 </body>
89 </html>

效果如下图:

posted @ 2017-01-07 14:33  时间脱臼  阅读(455)  评论(0)    收藏  举报