<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>原生JS实现动态折线图</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
let N = new CreateMovingLineDiagram();
//N.SetData.cavaswidth = 800//改变canvas宽度
N.play();
function CreateMovingLineDiagram() {
let _this = this;
//默认参数
_this.SetData = {
canvasid: "#canvas",// 画布ID
canvaswidth: 600,//画布宽度
canvasheight: 400,//画布高度
segmentationNum: 50,//分段数,将画布宽度分割成多少分
MoveSpeed: 100,//移动速度
IsShowsegmentationBool: true,//是否开启分段显示
IsCurveBool: true//true使用曲线绘图,false使用直线绘图
}
_this.play = function() {
let canvas = document.querySelector(_this.SetData.canvasid); //获取Canvas元素
canvas.width = _this.SetData.canvaswidth; //设置画布宽
canvas.height = _this.SetData.canvasheight; //设置画布高
let context = canvas.getContext("2d"); //使用Context绘画2D
let segmentation = _this.SetData.segmentationNum //分段数
let Speed = _this.SetData.MoveSpeed //绘画速度
let XYAttr = []; //分段坐标数组
let XZ = canvas.width / segmentation //得到每一段的X坐标
let XW = 0; //已生成的X坐标
let IsShowsegmentation = _this.SetData.IsShowsegmentationBool; //是否显示分段线
let IsCurve = _this.SetData.IsCurveBool; //是否绘画曲线
//进入页面先创建空数组
for (var i = 0; i < segmentation + 1; i++) {
XYAttr.push({
"X": XW,
"Y": canvas.height / 2
})
if (XW != canvas.width) {
XW += XZ;
}
}
setInterval(function() {
canvas.height = canvas.height; //先清除画布
if (IsShowsegmentation) {
for (var i = 0; i < segmentation + 1; i++) {
//画线
context.moveTo((i * XZ), 0);
context.lineTo((i * XZ), canvas.height)
context.strokeStyle = "#aaa";
context.stroke();
context.beginPath();
}
}
for (var i = 0; i < XYAttr.length; i++) {
if (IsCurve) {
//绘制曲线
if (i > 0) {
context.beginPath();
context.moveTo(XYAttr[i - 1].X, XYAttr[i - 1].Y);
context.quadraticCurveTo(XYAttr[i - 1].X, XYAttr[i].Y, XYAttr[i].X, XYAttr[i].Y);
}
} else {
//绘制直线
if (i > 0) {
context.beginPath();
context.moveTo(XYAttr[i - 1].X, XYAttr[i - 1].Y);
context.lineTo(XYAttr[i].X, XYAttr[i].Y)
}
}
context.strokeStyle = "coral";
context.stroke();
}
XYAttr.splice(0, 1);
//随机数据
round = Math.floor(Math.random() * canvas.height);
for (var i = 0; i < XYAttr.length; i++) {
XYAttr[i].X = XYAttr[i].X - (XZ * 2)
}
XYAttr.push({
"X": XW,
"Y": round
})
}, Speed)
}
}
</script>
</body>
</html>
请看效果