class Linechart {
ele: any
data: any
ctx: any
width: number
height: number
padding: number
randerData: any
x:number
y:number
constructor(ele: any, data: any) {
this.ele = ele,
this.data = data
this.ctx = this.ele.getContext('2d')//获取canvas工具箱
//获取canvas长宽
this.width = this.ele.width
this.height = this.ele.height
//边距
this.padding = 20
//坐标
this.x=this.padding
this.y=this.height-this.padding
//加工后数组,以坐标轴原点为零点
this.randerData = []
//统一初始化
this.init(this.data)
}
init(data: any) {
this.axis()
this.transformData(data)
this.paintDot(this.randerData)
this.paintLine(this.randerData)
}
axis() {
//x轴
this.ctx.beginPath()
this.ctx.moveTo(this.x, this.y);
this.ctx.lineTo(this.width - this.x, this.y);
this.ctx.lineTo(this.width - this.x - 5, this.y + 5)
this.ctx.lineTo(this.width - this.x - 5, this.y - 5)
this.ctx.lineTo(this.width - this.x, this.y);
this.ctx.stroke();
this.ctx.fill()
//y轴
this.ctx.beginPath()
this.ctx.moveTo(this.x, this.y)
this.ctx.lineTo(this.x, this.x)
this.ctx.lineTo(this.x + 5, this.x + 5)
this.ctx.lineTo(this.x - 5, this.x + 5)
this.ctx.lineTo(this.x, this.x)
this.ctx.stroke();
this.ctx.fill()
}
transformData(data: any) {//转化数据,以坐标轴原点为零点
this.randerData = data.map((item: any) => {
return {
x: item.x + this.x,
y: this.height - item.y + this.x
}
})
console.log(this.randerData)
}
paintDot(data: any) {//画点
data.forEach((item: any) => {
this.ctx.beginPath()
this.ctx.moveTo(item.x, item.y)
this.ctx.lineTo(item.x + 3, item.y + 3)
this.ctx.lineTo(item.x - 3, item.y + 3)
this.ctx.lineTo(item.x - 3, item.y - 3)
this.ctx.lineTo(item.x + 3, item.y - 3)
this.ctx.lineTo(item.x + 3, item.y + 3)
this.ctx.stroke();
this.ctx.fill()
});
}
paintLine(data: any) {//连线
this.ctx.beginPath()
this.ctx.moveTo(this.x, this.y);
data.forEach((item: any) => {
this.ctx.lineTo(item.x, item.y)
});
this.ctx.stroke();
}
}
const data: any = [
{ x: 50, y: 100 },
{ x: 120, y: 140 },
{ x: 150, y: 103 },
{ x: 189, y: 120 },
{ x: 200, y: 240 },
{ x: 400, y: 320 },
]
const canvas = document.querySelector('#canvas')
const line = new Linechart(canvas, data)
console.log(line);
//第一步先准备canvas工具箱
//第二步初始化数据
//第三步画坐标轴
//第四步画点
//第五步画线
用canvas画折线图
于 2022-02-13 17:40:18 首次发布