下面我们来简单介绍一下实现这款HTML5图表的过程以及源代码。
HTML代码:
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
简单的一个canvas标签,我们的图表就是在canvas上绘制而成的。
由于这款图表是基于RGraph的,所以我们还要引用RGraph的相关js脚本以及jquery类库:
复制代码
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.effects.js" ></script>
<script src="../libraries/RGraph.common.dynamic.js" ></script>
<script src="../libraries/RGraph.common.tooltips.js" ></script>
<script src="../libraries/RGraph.drawing.poly.js" ></script>
<script src="../libraries/RGraph.line.js" ></script>
<script src="../libraries/jquery.min.js" ></script>
复制代码
最后是Javascript代码:
复制代码
var d1 = [];
var d2 = [];
var val = 47;
// Create the data
for (var i=0; i<100; i+=1) d1[i] = RGraph.random(45,55);
for (var i=0; i<100; i+=1) d2[i] = RGraph.random(25,35);
var line = new RGraph.Line('cvs', d1, d2)
.Set('background.grid.autofit.numhlines', 10)
.Set('hmargin', 10)
.Set('filled', true)
.Set('fillstyle', 'red')
.Set('filled.range', true)
.Set('filled.range.threshold',40)
.Set('filled.range.threshold.colors', ['rgba(255,0,0,0.5)', 'rgba(0,0,255,0.5)'])
.Set('labels',['Q1','Q2','Q3','Q4'])
.Set('colors', ['gray', 'gray'])
.Set('numxticks', 8)
.Set('linewidth', 1)
.Set('ymax', 60)
RGraph.Effects.Line.jQuery.Trace(line);
var coords = []
for (var i=0; i<(line.coords.length/2); i+=1) {
coords.push(line.coords[i])
}
for (var i=(line.coords.length - 1); i>=(line.coords.length/2); i-=1) {
coords.push(line.coords[i])
}
var poly = new RGraph.Drawing.Poly('cvs', coords)
.Set('fillstyle', 'rgba(0,0,0,0)')
.Set('strokestyle', 'rgba(0,0,0,0)')
.Set('tooltips', ['The range chart'])
.Set('highlight.fill', 'rgba(255,255,255,0.3)')
.Draw();