本文主要是介绍canvas 画折线图方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
function creatCanvas(){//需要传入的数据var data = [80,92,104,110,68,50,45];//需要传入的x坐标var time =["11","1.1","13.1","14.1","15.1","16.1","17.1"];// 获取上下文var a_canvas = document.getElementById('a_canvas');var context = a_canvas.getContext("2d");// 描绘边框var grid_cols = data.length + 1;var grid_rows = 4;var cell_height =(a_canvas.height-50)/ grid_rows;var cell_width = a_canvas.width / grid_cols;context.lineWidth = 1;context.strokeStyle = "#a0a0a0";context.beginPath();context.moveTo(0,0);// 准备画横线var y = grid_rows*cell_height;context.moveTo(0,y);context.lineTo(a_canvas.width, y);context.moveTo(1,0);context.lineTo(1,a_canvas.height-50);context.lineWidth = 2;context.strokeStyle = "#c0c0c0";context.stroke();var max_v = 0;for(var i = 0; i<data.length; i++){if (data[i] > max_v) { max_v = data[i]};}max_v = max_v * 1.1;// 将数据换算为坐标var points = [];for( var i=0; i < data.length; i++){var v= data[i];var px = cell_width * (i+1);var py = (a_canvas.height-50) - (a_canvas.height-50)*(v / max_v);points.push({"x":px,"y":py});}// 绘制折线context.beginPath();context.moveTo(points[0].x, points[0].y);for(var i= 1; i< points.length; i++){context.lineTo(points[i].x,points[i].y);}context.lineWidth = 2;context.strokeStyle = "#ee0000";context.stroke();//绘制坐标图形for(var i in points){var p = points[i];context.beginPath();context.arc(p.x,p.y,4,0,2*Math.PI);context.fillStyle = "#ee0000";context.fill();}//画x轴for(var i in points){var p = points[i];context.beginPath();context.arc(p.x,y,2,0,2*Math.PI);context.fillStyle = "#ee0000";context.fill();context.beginPath();context.font = 'thick 6px arial';context.fillStyle = "green";context.fillText(time[i], p.x-time[i].length*3, y+15);}context.beginPath();context.font = 'thick 10px arial';context.fillStyle = "green";context.fillText("y轴", 0, 10);//}
这篇关于canvas 画折线图方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!