HTML5 Canvas 折线图

html5 canvas 实现折线图表



.canbox{ width:550px; margin:50px auto;}
.canbox canvas { margin: 0 auto; display: block; background-image: linear-gradient(  transparent 0,  #fff 20px,  #f5f5f5 20px,  #f5f5f5 40px,  transparent 40px,  transparent 60px,  #f5f5f5 60px,  #f5f5f5 80px,  transparent 80px,  transparent 100px,  #f5f5f5 100px,  #f5f5f5 120px,  transparent 120px,  transparent 140px,  #f5f5f5 140px,  #f5f5f5 160px,  transparent 160px,  transparent 180px,  #f5f5f5 180px,  #f5f5f5 200px); border: solid 1px #ddd; }
#txt{ width:100%; height:30px; text-align:center; display:block; margin:10px auto; color:#090; border:0; background:#f5f5f5;}
<div class="canbox">
	<input type="text" readonly id="txt">
	<canvas width="550" height="200" id="mycanvas"></canvas>
	<button id="refresh" style="display:block;">刷新</button>
</div>
/*
 @ Aame:canvas 折线图
 @ Author:前端老徐
 @ Date:2015/10/24
 @ E-mail:442413729@qq.com
 @ Weibo:http://weibo.com/qdlaoxu
 @ Address:http://www.loveqiao.com
*/
function LineChart(){
	this.w=550;
	this.h=200;
	this.data=null;
	this.oCan=document.getElementById('mycanvas');
	this.ctx=this.oCan.getContext('2d');
}
LineChart.prototype={
	init:function(d){
		//刷新
		var n,_self=this;
		_self.data=d
		document.getElementById('refresh').onclick=function(){
			_self.ctx.clearRect(0,0,_self.w,_self.h)
			for(n in _self.data){
				_self.data[n]=Math.floor(Math.random()*100)
			}
			_self.draw();
		}
		_self.draw();
	},
	//绘制
	draw:function(){
		document.getElementById('txt').value=this.data
		this.ctx.beginPath()
		for(n in this.data){
			var x=n*50,y=200-(this.data[n])*2
			if(n==0){
				this.ctx.moveTo(x,y);
			}else{
				this.ctx.lineTo(x,y);
			}
			//ctx.arc(
		}
		this.ctx.strokeStyle='#f00';
		this.ctx.stroke();
	}
}
var fn=new LineChart();
fn.init([2,55,66,32,67,32,67,23,77,22,43,66]);

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>