<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="800" height="800" style="border: 1px solid #cccccc;"></canvas>
</body>
</html>
<script>
//1.创建构造函数
var LineChart = function () {
//获取绘图工具
this.ctx = document.querySelector('canvas').getContext('2d');
this.canvasW = this.ctx.canvas.width;
this.canvasH = this.ctx.canvas.height;
//格子的大小
this.size = 10 ;
//坐标系的间距
this.space = 20;
//坐标的原点
this.x0 = this.space;
this.y0 = this.canvasH - this.space;
//箭头的大小
this.arrowSize = 10;
//点的大小
this.pointSize = 6;
};
//2.添加行为方法 -->在原型上添加
//初始化折线图
LineChart.prototype.init = function () {
this.drawGird();
this.drawAxis();
this.drawPoint(data);
};
//绘制网格
LineChart.prototype.drawGird = function () {
//1.X方向的线
var lineX = Math.floor(this.canvasH/this.size);
for (var i = 0 ; i < lineX ; i++){
this.ctx.beginPath();
this.strokeStyle = '#cccccc';
this.ctx.moveTo(0,i*this.size-0.5);
this.ctx.lineTo(this.canvasW,i*this.size-0.5);
this.ctx.stroke();
}
//1.Y方向的线
var lineY = Math.floor(this.canvasH/this.size);
for (var i = 0 ; i < lineY ; i++){
this.ctx.beginPath();
this.strokeStyle = '#cccccc';
this.ctx.moveTo(i*this.size-0.5,0);
this.ctx.lineTo(i*this.size-0.5,this.canvasH,);
this.ctx.stroke();
}
};
//绘制坐标系
LineChart.prototype.drawAxis = function () {
//x轴
this.ctx.beginPath();
this.ctx.strokeStyle = 'red';
this.ctx.fillStyle = 'red';
this.ctx.moveTo(this.x0,this.y0);
this.ctx.lineTo(this.canvasW - this.space,this.y0);
this.ctx.lineTo(this.canvasW - this.space - this.arrowSize,this.y0+this.arrowSize/2);
this.ctx.lineTo(this.canvasW - this.space - this.arrowSize,this.y0-this.arrowSize/2);
this.ctx.lineTo(this.canvasW - this.space,this.y0);
this.ctx.stroke();
this.ctx.fill();
//Y轴
this.ctx.beginPath();
this.ctx.strokeStyle = 'red';
this.ctx.fillStyle = 'red';
this.ctx.moveTo(this.x0,this.y0);
this.ctx.lineTo(this.space,this.space);
this.ctx.lineTo(this.space + this.arrowSize/2,this.space+this.arrowSize);
this.ctx.lineTo(this.space - this.arrowSize/2,this.space + this.arrowSize);
this.ctx.lineTo(this.space,this.space);
this.ctx.stroke();
this.ctx.fill();
};
//绘制所有的点
LineChart.prototype.drawPoint = function (data) {
//1.数据的坐标转化为canvas坐标
//2.绘制点
//3.把线连起来
var that = this; //函数嵌套,this的指向发生变化
var prevX = 0;
var prevY = 0;
data.forEach(function (item,i) {
var canvasX = that.x0 + item.x;
var canvasY = that.y0 - item.y;
//绘制点
that.ctx.beginPath();
that.ctx.fillRect(canvasX - that.pointSize / 2,canvasY - that.pointSize/2,that.pointSize,that.pointSize);
if (i == 0){
that.ctx.moveTo(that.x0,that.y0);
that.ctx.lineTo(canvasX,canvasY);
that.ctx.stroke();
}else{
that.ctx.moveTo(prevX,prevY);
that.ctx.lineTo(canvasX,canvasY);
that.ctx.stroke();
}
//纪录下一条开始的坐标
prevX = canvasX;
prevY = canvasY;
})
};
//初始化数据的坐标
var data = [
{
x:100,
y:100
},
{
x:200,
y:100
},
{
x:300,
y:300
},
{
x:500,
y:200
},
{
x:600,
y:600
},
]
//3.创建对象
var lineChart = new LineChart();
lineChart.init();
</script>
用画布制作折线图
最新推荐文章于 2023-04-12 10:17:48 发布