canvas绘制折线图
- 2019-01-05 10:23:22
- 4,261 次阅读
- 2
折线图无论是在日常工作中还是学习当中经常都能够被用到,因为它非常直观地反映出数据的变化趋势,而被人们广泛应用于各个行业和领域。大家都知道word和excel具有制作各种图表的功能,当然制作折线图也不在话下。但你是否尝试过用HTML5提供的画布(canvas)来绘制折线图呢?下面是代码实现的过程。
(1)折线图:
(2)canvas绘图代码:
var canvas = document.getElementById("demo"); canvas.width = 600; canvas.height = 600; canvas.style.border = "1px solid #000"; var ctx = canvas.getContext("2d"); var width = 20; var height = 20; var maxX = 400; var maxY = 400; for(var i = 1 ; i< canvas.width / width ; i ++){ ctx.beginPath(); ctx.moveTo( i * width , 0); ctx.lineTo( i * width , canvas.height); ctx.stroke(); } for(var i = 1 ; i< canvas.height / height ; i ++){ ctx.beginPath(); ctx.moveTo( 0, i * height); ctx.lineTo( canvas.width , i * height); ctx.stroke(); } var circle = {x0: 100 , y0: 500}; //绘制x轴 ctx.beginPath(); ctx.moveTo(circle.x0 , circle.y0) ctx.lineTo(circle.x0 ,circle.y0 - maxY); ctx.lineTo(100 - width/2 ,100 + height/2); ctx.moveTo(100, 100) ctx.lineTo(100 + width/2 , 100 + height/2); ctx.lineWidth = 3; ctx.strokeStyle = "red"; ctx.stroke(); //绘制y轴 ctx.beginPath(); ctx.moveTo(circle.x0 , circle.y0); ctx.lineTo(circle.x0 + maxX , circle.y0 ); ctx.lineTo(circle.x0 + maxX - width/2 , circle.y0 - height/2); ctx.moveTo(circle.x0 + maxX, circle.y0); ctx.lineTo(circle.x0 + maxX - width/2 ,circle.y0 + height/2 ); ctx.lineWidth = 3; ctx.strokeStyle = "blue"; ctx.stroke(); //通过给定的数据绘制出折线 每个占100的多少,如第一个占40% var data = [40, 48, 50, 70, 60, 40, 20, 60, 80, 90]; //得到每一个点之间的距离 var widthX = maxX / data.length;//平均分成10份,每份占40 //开始绘制折线 ctx.beginPath(); ctx.moveTo(circle.x0, circle.y0); for(var i = 0 ; i <=data.length ; i++){ ctx.lineTo(circle.x0 + (i +1 )* widthX, circle.y0 - data[i]/ 100 * maxY); ctx.strokeStyle = "red"; ctx.stroke(); }
文章评论 (0)