HTML5 canvas画一个折线图

时间:2023-02-14 12:01:35


HTML5 canvas画一个折线图

<body>
<canvas style="border:1px solid;" width="600" height="400"></canvas>
<script type="text/javascript">
let drawing = document.querySelector("#drawing");
let context = drawing.getContext("2d");
//1,画线
context.strokeStyle = '#ccc';
let space = 10; //每条线的间距
let width = context.canvas.width; //600 画布的宽度
let height = context.canvas.height; //400 画布的高度
let arrow = 10; //坐标轴箭头的中线
let arrowFloor = 10; //坐标轴箭头的底线
//竖线
for (var i = 0; i < width / space; i++) {
context.beginPath();
context.moveTo(i * space - 0.5, 0);
context.lineTo(i * space - 0.5, height)
context.stroke();
}
//横线
for (var i = 0; i < height / space; i++) {
context.beginPath();
context.moveTo(0, i * space - 0.5);
context.lineTo(width, i * space - 0.5)
context.stroke();
}
//画坐标系
//圆心坐标
let x0 = space-0.5;
let y0 = height - space-0.5;
//y 轴
context.strokeStyle = '#333';
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x0, space);
context.stroke();
//y轴的箭头
context.beginPath();
context.moveTo(x0, space);
context.lineTo(x0 - arrowFloor / 2, space + arrow);
context.lineTo(x0 + arrowFloor / 2, space + arrow);
context.lineTo(x0, space);
context.fill();
context.stroke();
//x 轴
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(width - space, height - space);
//x 轴箭头
context.lineTo(width - space - arrow, height - space - arrowFloor / 2);
context.lineTo(width - space - arrow, height - space + arrowFloor / 2);
context.lineTo(width - space, height - space);
context.fill();
context.stroke();

//封装一个方法-画点-方形square
function drawSquare(element, x, y, w, h) {
element.beginPath();
element.moveTo(x - w / 2, y - h / 2);
element.lineTo(x + w / 2, y - h / 2);
element.lineTo(x + w / 2, y + h / 2);
element.lineTo(x - w / 2, y + h / 2);
element.closePath();
element.fill();
element.stroke();
}
//数据
let data = [{
x: 100,
y: 100
}, {
x: 150,
y: 220
},{
x: 250,
y: 120
},{
x: 350,
y: 220
},{
x: 390,
y: 300
},{
x: 440,
y: 320
}];
//将数据由转换成canvas上的数据

//连线
let prevX = space+data[0].x;//上一个点的坐标 为连线做准备
let prevY = height-space-data[0].y;
data.forEach((item,index,data)=>{
item.x = space+item.x;
item.y = height-space-item.y;
//画点
drawSquare(context, item.x, item.y, 5, 5);
//连线
context.beginPath();
context.moveTo(prevX,prevY);
context.lineTo(item.x,item.y);
context.stroke();
prevX = item.x;
prevY = item.y;
})




</script>
</body>