js实现曲线图
使用 Canvas 绘制曲线图
Canvas 是 HTML5 提供的绘图 API,适合动态生成图形。以下是一个简单的曲线图实现示例:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制坐标轴
ctx.beginPath();
ctx.moveTo(50, 30);
ctx.lineTo(50, 250);
ctx.lineTo(450, 250);
ctx.stroke();
// 绘制曲线
ctx.beginPath();
ctx.moveTo(50, 250);
const points = [60, 120, 90, 80, 150, 200, 210, 150, 270, 180, 330, 100, 390, 160];
for (let i = 0; i < points.length; i += 2) {
ctx.lineTo(50 + points[i], 250 - points[i+1]);
}
ctx.strokeStyle = 'blue';
ctx.stroke();
使用 SVG 绘制曲线图
SVG 是矢量图形格式,适合需要缩放和交互的场景:
const svg = document.getElementById('mySvg');
const pathData = points.reduce((acc, val, i) => {
return acc + (i % 2 === 0 ? ` L${50 + val}` : ` ${250 - val}`);
}, `M50 250`);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', pathData);
path.setAttribute('stroke', 'blue');
path.setAttribute('fill', 'none');
svg.appendChild(path);
使用 Chart.js 库
Chart.js 是流行的图表库,简化了图表创建过程:
const ctx = document.getElementById('myChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
datasets: [{
label: 'Sales',
data: [65, 59, 80, 81, 56, 55],
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
使用 D3.js 库
D3.js 提供更强大的数据可视化功能:
const data = [10, 20, 30, 40, 50, 60];
const svg = d3.select('#d3Chart')
.append('svg')
.attr('width', 400)
.attr('height', 300);
const line = d3.line()
.x((d, i) => i * 60 + 50)
.y(d => 250 - d * 3)
.curve(d3.curveCardinal);
svg.append('path')
.datum(data)
.attr('fill', 'none')
.attr('stroke', 'steelblue')
.attr('stroke-width', 2)
.attr('d', line);
实现平滑曲线
使用贝塞尔曲线实现平滑效果:
ctx.beginPath();
ctx.moveTo(50, 250);
for (let i = 0; i < points.length - 2; i += 2) {
const xc = (points[i] + points[i+2]) / 2;
const yc = (points[i+1] + points[i+3]) / 2;
ctx.quadraticCurveTo(
50 + points[i], 250 - points[i+1],
50 + xc, 250 - yc
);
}
ctx.stroke();
响应式设计
使图表适应不同屏幕尺寸:

function resizeCanvas() {
const container = document.getElementById('chartContainer');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
drawChart(); // 重新绘制图表
}
window.addEventListener('resize', resizeCanvas);
以上方法提供了从基础到高级的曲线图实现方案,可根据项目需求选择合适的技术方案。






