Canvas之画单一折线图

Canvas折线图

Posted by LuochuanAD on June 14, 2017 本文总阅读量

前言

使用HTML画单一折线图,效果图如下; 我只需要画折现和小圆就可以了.

详细代码CanvasForHtml5已上传到Github

分析

<canvas id="a_canvas" width="950" height="300"></canvas>



<script type="text/javascript">
(function (){

window.addEventListener("load", function(){

var data = [501,501,437,437,468,2107,2107,2110,1800,1800,1600,1400,1400,1500,1600,1400,1500,1700,1900];

// 获取上下文
var a_canvas = document.getElementById('a_canvas');
var context = a_canvas.getContext("2d");
var minDataValue=100000000;
for (var i = 0; i<data.length; i++) {
var barVal = parseInt(data[i]);
if (parseInt(barVal) < parseInt(minDataValue))
minDataValue = barVal;
}

// 绘制背景
var gradient = context.createLinearGradient(0,0,0,300);


// gradient.addColorStop(0,"#e0e0e0");
//gradient.addColorStop(1,"#ffffff");


context.fillStyle = gradient;

context.fillRect(0,0,a_canvas.width,a_canvas.height);


// 描绘边框
var grid_cols = data.length + 1;
var grid_rows = 4;
var cell_height = a_canvas.height / grid_rows;
var cell_width = a_canvas.width / grid_cols;
context.lineWidth = 4;
context.strokeStyle = "#a0a0a0";



var max_v =0;

for(var i = 0; i<data.length; i++){
var d=0;
if(data[i]<0)
{d=d-data[i];
}
else{d=data[i];};
if (d > max_v) { max_v =d};
}
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 - a_canvas.height*(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 = 4;
context.strokeStyle = "white";
context.stroke();



//绘制坐标图形
for(var i in points){
var p = points[i];
context.beginPath();
context.lineWidth = 4;
context.radius = 4;
context.arc(p.x,p.y,7,0,2*Math.PI);
//实心圆
/*
context.fillStyle = "#000";*/
//空心圆
context.strokeStyle = "white";
context.stroke();
context.fillStyle="#009CEF";
context.fill();
}

//添加文字
//        for(var i in points)
//        {  var p = points[i];
//          context.beginPath();
//          context.fillStyle="black";
//          context.fillText(data[i], p.x + 1, p.y - 15);
//             
//            }

context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
context.strokeStyle = "white"; //设置描边样式
context.fillStyle="white";

context.font = "40px sans-serif"; //设置字体大小和字体

//绘制字体,并且指定位置
context.fillText("0", a_canvas.width*0.97, a_canvas.height*0.98);

context.stroke();//执行绘制

context.restore();
},false);
})();

</script>


结语

博客旧版原文在CSDN上:https://blog.csdn.net/luochuanAD/article/details/73252037