js实现实时绘图
实时绘图实现方法(JavaScript)
使用Canvas API绘制动态图形
创建HTML5 Canvas元素作为绘图区域
<canvas id="realTimeChart" width="600" height="400"></canvas>
初始化Canvas上下文并设置基础样式
const canvas = document.getElementById('realTimeChart');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 2;
实现数据更新与重绘逻辑
let dataPoints = [];
function updateData(newValue) {
dataPoints.push(newValue);
if(dataPoints.length > 50) {
dataPoints.shift();
}
drawChart();
}
基于requestAnimationFrame的动画循环
优化绘制性能的动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawDataLine();
requestAnimationFrame(animate);
}
animate();
实现平滑的折线图绘制
function drawDataLine() {
ctx.beginPath();
const step = canvas.width / (dataPoints.length - 1);
dataPoints.forEach((value, index) => {
const x = index * step;
const y = canvas.height - value * canvas.height / 100;
index === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
});
ctx.stroke();
}
实时数据获取与绑定
模拟实时数据源
setInterval(() => {
const newValue = Math.random() * 80 + 10;
updateData(newValue);
}, 100);
实际应用时可替换为WebSocket数据
const socket = new WebSocket('wss://data-source.example.com');
socket.onmessage = (event) => {
updateData(parseFloat(event.data));
};
性能优化技巧
采用双缓冲技术减少闪烁
const bufferCanvas = document.createElement('canvas');
bufferCanvas.width = canvas.width;
bufferCanvas.height = canvas.height;
const bufferCtx = bufferCanvas.getContext('2d');
function drawToBuffer() {
bufferCtx.clearRect(0, 0, bufferCanvas.width, bufferCanvas.height);
// 在缓冲画布上绘制所有内容
}
function render() {
ctx.drawImage(bufferCanvas, 0, 0);
requestAnimationFrame(render);
}
响应式布局处理
添加窗口大小变化的响应处理
window.addEventListener('resize', () => {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
drawChart();
});
高级可视化增强
添加坐标轴和刻度
function drawAxes() {
ctx.beginPath();
// X轴
ctx.moveTo(0, canvas.height - 20);
ctx.lineTo(canvas.width, canvas.height - 20);
// Y轴
ctx.moveTo(20, 0);
ctx.lineTo(20, canvas.height);
ctx.stroke();
}
实现数据点标记

function drawDataPoints() {
ctx.fillStyle = '#e74c3c';
const step = canvas.width / (dataPoints.length - 1);
dataPoints.forEach((value, index) => {
const x = index * step;
const y = canvas.height - value * canvas.height / 100;
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
});
}






