js实现曲线图
使用 Canvas API 绘制曲线图
Canvas 是 HTML5 提供的绘图 API,适合动态生成复杂图形。以下示例展示如何绘制简单的正弦曲线:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置画布样式
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 2;
// 绘制坐标轴
ctx.beginPath();
ctx.moveTo(50, 150);
ctx.lineTo(350, 150);
ctx.moveTo(200, 50);
ctx.lineTo(200, 250);
ctx.stroke();
// 绘制正弦曲线
ctx.beginPath();
for (let x = -180; x <= 180; x += 5) {
const y = Math.sin(x * Math.PI / 180) * 80;
if (x === -180) {
ctx.moveTo(x + 200, -y + 150);
} else {
ctx.lineTo(x + 200, -y + 150);
}
}
ctx.stroke();
使用 SVG 实现曲线图
SVG 是矢量图形标准,适合需要缩放或交互的场景:
<svg width="400" height="300" viewBox="0 0 400 300">
<!-- 坐标轴 -->
<line x1="50" y1="150" x2="350" y2="150" stroke="#333"/>
<line x1="200" y1="50" x2="200" y2="250" stroke="#333"/>
<!-- 曲线路径 -->
<path d="M50,150 Q125,50 200,150 T350,150"
fill="none"
stroke="#e74c3c"
stroke-width="2"/>
</svg>
使用 Chart.js 库创建曲线图
Chart.js 是流行的图表库,简化了复杂图表的创建:
const ctx = document.getElementById('chartCanvas').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Sales 2023',
data: [65, 59, 80, 81, 56],
borderColor: 'rgb(75, 192, 192)',
tension: 0.3,
fill: false
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
使用 D3.js 创建高级曲线图
D3.js 适合需要高度定制化的数据可视化:
const data = [0, 0.5, 0.8, 0.3, 0.6, 1];
const svg = d3.select("#d3-chart")
.append("svg")
.attr("width", 400)
.attr("height", 300);
const xScale = d3.scaleLinear()
.domain([0, data.length-1])
.range([50, 350]);
const yScale = d3.scaleLinear()
.domain([0, 1])
.range([250, 50]);
const line = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d))
.curve(d3.curveCardinal);
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
响应式曲线图实现
确保图表适应不同屏幕尺寸:
function resizeChart() {
const container = document.getElementById('chart-container');
const aspectRatio = 16 / 9;
const width = container.clientWidth;
const height = width / aspectRatio;
canvas.width = width;
canvas.height = height;
// 重绘图表逻辑
drawChart();
}
window.addEventListener('resize', resizeChart);
resizeChart();
曲线图动画效果
为曲线添加平滑的绘制动画:
function animateLine(ctx, points, duration) {
const startTime = performance.now();
function draw(timestamp) {
const progress = (timestamp - startTime) / duration;
if (progress > 1) progress = 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
const visiblePoints = Math.floor(points.length * progress);
for (let i = 0; i < visiblePoints; i++) {
if (i === 0) {
ctx.moveTo(points[i].x, points[i].y);
} else {
ctx.lineTo(points[i].x, points[i].y);
}
}
ctx.stroke();
if (progress < 1) {
requestAnimationFrame(draw);
}
}
requestAnimationFrame(draw);
}
以上方法涵盖了从原生实现到使用流行库的不同方案,可根据项目需求选择合适的技术路径。Canvas 适合性能要求高的场景,SVG 适合需要矢量缩放的情况,Chart.js 适合快速开发标准图表,D3.js 则提供最大灵活性。







