js实现图例
使用 Canvas 绘制图例
Canvas 提供基础的绘图 API,适合自定义图例样式:
const canvas = document.getElementById('legendCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形图例
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 30, 20);
ctx.font = '12px Arial';
ctx.fillText('Series 1', 50, 25);
// 绘制圆形图例
ctx.beginPath();
ctx.arc(10, 50, 8, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.fillText('Series 2', 50, 55);
使用 SVG 创建动态图例
SVG 图例支持交互和动态更新:
const svg = document.getElementById('legendSvg');
// 添加矩形元素
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '30');
rect.setAttribute('height', '20');
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
// 添加文本标签
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '50');
text.setAttribute('y', '25');
text.textContent = 'Data Set';
svg.appendChild(text);
基于 CSS 的 HTML 图例
纯 HTML/CSS 方案适合简单场景:
<div class="legend">
<div class="legend-item">
<span class="color-box" style="background: #FF6384;"></span>
<span>First Dataset</span>
</div>
<div class="legend-item">
<span class="color-box" style="background: #36A2EB;"></span>
<span>Second Dataset</span>
</div>
</div>
<style>
.legend {
display: flex;
flex-direction: column;
gap: 8px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.color-box {
width: 20px;
height: 20px;
border-radius: 3px;
}
</style>
集成图表库的图例
常见图表库如 Chart.js 自动生成图例:
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb'],
datasets: [{
label: 'Sales',
data: [12, 19],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)'
}]
},
options: {
plugins: {
legend: {
position: 'right',
labels: {
font: {
size: 14
}
}
}
}
}
});
响应式图例实现
通过监听窗口变化调整图例布局:
function updateLegendLayout() {
const width = window.innerWidth;
const legend = document.querySelector('.legend');
if (width < 600) {
legend.style.flexDirection = 'column';
} else {
legend.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');
});
});
自定义图例符号
使用 Unicode 或 CSS 创建特殊符号:
.legend-custom::before {
content: "◆";
color: var(--symbol-color);
margin-right: 5px;
font-size: 1.2em;
}
图例分页控制
处理大量图例项的分页显示:
let currentPage = 0;
const itemsPerPage = 5;
function showLegendPage(page) {
const items = document.querySelectorAll('.legend-item');
items.forEach((item, index) => {
item.style.display = (index >= page * itemsPerPage &&
index < (page + 1) * itemsPerPage) ? 'flex' : 'none';
});
}






