<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas width="600" height="400" style="border: 1px solid #ccc"></canvas>
<script>
//构造函数
var LineChart = function () {
//画笔
this.ctx = document.querySelector('canvas').getContext('2d');
//格子宽度
this.size = 10;
//画布宽,高
this.canvasW = this.ctx.canvas.width;
this.canvasH = this.ctx.canvas.height;
//轴间距
this.space = 20;
//箭头大小
this.ArrowSize = 10;
//坐标轴原点
this.axisX = this.space;
this.axisY = this.canvasH - this.space;
//点边长
this.pointW = 6;
}
//原型
LineChart.prototype.init = function(){
this.grid();
this.axis();
this.point(data);
}
//网格
LineChart.prototype.grid = function(){
this.ctx.strokeStyle = '#ccc';
//与x轴平行线
var linerX = Math.floor(this.canvasH/this.size);
for (var i = 0; i < linerX; i++) {
this.ctx.beginPath();
this.ctx.moveTo(0,i*this.size-0.5);
this.ctx.lineTo(this.canvasW,i*this.size-0.5);
this.ctx.stroke();
}
//与y轴平行线
var linery = Math.floor(this.canvasW/this.size);
for (var i = 0; i < linery; i++) {
this.ctx.beginPath();
this.ctx.moveTo(i*this.size-0.5,0);
this.ctx.lineTo(i*this.size-0.5,this.canvasH);
this.ctx.stroke();
}
}
//坐标轴
LineChart.prototype.axis = function(){
console.log(this.canvasW-this.space,this.axisY);
//x轴
this.ctx.beginPath();
this.ctx.strokeStyle = '#000';
this.ctx.moveTo(this.axisX,this.axisY);
this.ctx.lineTo(this.canvasW-this.space,this.axisY);
this.ctx.lineTo(this.canvasW - this.space-this.ArrowSize,this.axisY+this.ArrowSize/2);
this.ctx.lineTo(this.canvasW-this.space-this.ArrowSize,this.axisY-this.ArrowSize/2);
this.ctx.lineTo(this.canvasW-this.space,this.axisY);
this.ctx.fill();
this.ctx.stroke();
//y轴
this.ctx.beginPath();
this.ctx.strokeStyle = '#000';
this.ctx.moveTo(this.axisX,this.axisY);
this.ctx.lineTo(this.axisX,this.space);
this.ctx.lineTo(this.axisX+this.ArrowSize/2,this.space+this.ArrowSize);
this.ctx.lineTo(this.axisX-this.ArrowSize/2,this.space+this.ArrowSize);
this.ctx.lineTo(this.axisX,this.space);
this.ctx.fill();
this.ctx.stroke();
}
//描点,连线
LineChart.prototype.point = function(data){
var this = this;
var prevX = 0;
var prevY = 0;
data.forEach(function(item,i){
//定义坐标轴
var pointX = this.axisX+item.x;
var pointY = this.axisY-item.y;
this.ctx.beginPath();
this.ctx.fillRect(pointX-this.pointW/2,pointY-this.pointW/2,this.pointW,this.pointW);
if (i == 0) {
this.ctx.moveTo(this.axisX,this.axisY);
this.ctx.lineTo(pointX,pointY);
this.ctx.stroke()
}else{
this.ctx.moveTo(prevX,prevY);
this.ctx.lineTo(pointX,pointY);
this.ctx.stroke()
}
prevX = pointX;
prevY = pointY;
})
}
var data = [
{
x:100,
y:100
},
{
x:200,
y:180
},
{
x:300,
y:250
},
{
x:400,
y:80
},
{
x:500,
y:50
},
]
//实例化对象
var lineChart = new LineChart();
lineChart.init();
</script>
</body>
</html>
面向对象思想,用canvas绘制折线图
最新推荐文章于 2021-08-07 02:42:35 发布