js实现图例
使用Canvas绘制图例
Canvas是HTML5提供的绘图API,适合动态生成图例。通过创建<canvas>元素并调用绘图方法实现。
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 20, 20);
ctx.font = '12px Arial';
ctx.fillText('数据系列1', 40, 25);
使用SVG创建图例
SVG是矢量图形标准,适合创建可缩放的图例。通过DOM操作创建SVG元素。
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '200');
svg.setAttribute('height', '100');
document.body.appendChild(svg);
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '20');
rect.setAttribute('height', '20');
rect.setAttribute('fill', 'blue');
svg.appendChild(rect);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '40');
text.setAttribute('y', '25');
text.setAttribute('font-size', '12');
text.textContent = '数据系列2';
svg.appendChild(text);
基于CSS的图例实现
纯CSS方案适合简单静态图例,利用伪元素和Flex布局。
<div class="legend">
<div class="legend-item">
<span class="legend-color" style="background: green"></span>
<span class="legend-label">数据系列3</span>
</div>
</div>
<style>
.legend {
display: flex;
flex-direction: column;
gap: 8px;
}
.legend-item {
display: flex;
align-items: center;
}
.legend-color {
width: 20px;
height: 20px;
margin-right: 10px;
}
</style>
使用第三方库生成图例
常见图表库如Chart.js、ECharts等内置图例功能。以Chart.js为例:
import { Chart } from 'chart.js';
new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: '数据集',
data: [10, 20, 30],
backgroundColor: 'orange'
}]
},
options: {
plugins: {
legend: {
position: 'right',
labels: {
font: { size: 14 }
}
}
}
}
});
响应式图例实现
通过监听窗口大小变化动态调整图例布局。
function updateLegendLayout() {
const width = window.innerWidth;
if (width < 768) {
legendElement.style.flexDirection = 'column';
} else {
legendElement.style.flexDirection = 'row';
}
}
window.addEventListener('resize', updateLegendLayout);
updateLegendLayout();
可交互图例实现
为图例添加点击事件实现系列显示/隐藏功能。
document.querySelectorAll('.legend-item').forEach(item => {
item.addEventListener('click', () => {
const datasetIndex = item.dataset.index;
chart.getDatasetMeta(datasetIndex).hidden =
!chart.getDatasetMeta(datasetIndex).hidden;
chart.update();
item.classList.toggle('disabled');
});
});






