用html5绘制折线图的实例代码

晨曦是朝气蓬勃的美少女,在你耳畔浅吟低唱,她身上带有露珠草香的味道,会飘香你一整天的心情,祝你每一天都!你多学一样本事,就少说一句求人的话。
XML/HTML Code复制内容到剪贴板
  1. <html>
  2. <canvasid="a_canvas"width="1000"height="700"></canvas>
  3. <script>
  4. (function(){
  5. window.addEventListener("load",function(){
  6. vardata=[100,-1000,0,700];
  7. //获取上下文
  8. vara_canvas=document.getElementById('a_canvas');
  9. varcontext=a_canvas.getContext("2d");
  10. //绘制背景
  11. vargradient=context.createLinearGradient(0,0,0,300);
  12. //gradient.addColorStop(0,"#e0e0e0");
  13. //gradient.addColorStop(1,"#ffffff");
  14. context.fillStyle=gradient;
  15. context.fillRect(0,0,a_canvas.width,a_canvas.height);
  16. //描绘边框
  17. vargrid_cols=data.length+1;
  18. vargrid_rows=4;
  19. varcell_height=a_canvas.height/grid_rows;
  20. varcell_width=a_canvas.width/grid_cols;
  21. context.lineWidth=1;
  22. context.strokeStyle="#a0a0a0";
  23. //结束边框描绘
  24. context.beginPath();
  25. //准备画横线
  26. /*for(varcol=0;col<=grid_cols;col++){
  27. varx=col*cell_width;
  28. context.moveTo(x,0);
  29. context.lineTo(x,a_canvas.height);
  30. }
  31. //准备画竖线
  32. for(varrow=0;row<=grid_rows;row++){
  33. vary=row*cell_height;
  34. context.moveTo(0,y);
  35. context.lineTo(a_canvas.width,y);
  36. }*/
  37. //划横线
  38. context.moveTo(0,a_canvas.height/2);
  39. context.lineTo(a_canvas.width,a_canvas.height/2);
  40. //画竖线
  41. context.moveTo(0,0);
  42. context.lineTo(0,a_canvas.height);
  43. context.lineWidth=1;
  44. context.strokeStyle="#c0c0c0";
  45. context.stroke();
  46. varmax_v=0;
  47. for(vari=0;i<data.length;i++){
  48. vard=0;
  49. if(data[i]<0)
  50. {dd=d-data[i];
  51. }
  52. else{d=data[i];};
  53. if(d>max_v){max_v=d};
  54. }
  55. max_vmax_v=max_v*1.1;
  56. //将数据换算为坐标
  57. varpoints=[];
  58. for(vari=0;i<data.length;i++){
  59. varv=data[i];
  60. varpx=cell_width* (i+1);
  61. varpy=a_canvas.height/2-a_canvas.height*(v/max_v)/2;
  62. points.push({"x":px,"y":py});
  63. }
  64. //绘制折现
  65. context.beginPath();
  66. context.moveTo(points[0].x,points[0].y);
  67. for(vari=1;i<points.length;i++){
  68. context.lineTo(points[i].x,points[i].y);
  69. }
  70. context.lineWidth=2;
  71. context.strokeStyle="#8BA9FF";
  72. context.stroke();
  73. //绘制坐标图形
  74. for(variinpoints){
  75. varp=points[i];
  76. context.beginPath();
  77. context.arc(p.x,p.y,4,0,2*Math.PI);
  78. //实心圆
  79. /*
  80. context.fillStyle="#000";*/
  81. //空心圆
  82. context.strokeStyle="#000";
  83. context.stroke();
  84. context.fillStyle="white";
  85. context.fill();
  86. }
  87. //添加文字
  88. for(variinpoints)
  89. {varp=points[i];
  90. context.beginPath();
  91. context.fillStyle="black";
  92. context.fillText(data[i],p.x+1,p.y-15);
  93. }
  94. },false);
  95. })();
  96. </script>
  97. </html>

运行结果如下:

以上这篇用html5绘制折线图的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

原文地址:http://www.cnblogs.com/shuniuniu/archive/2016/03/25/5318717.html

标签: 折线图