js实现图例
使用Canvas绘制图例
Canvas是HTML5提供的绘图API,适合动态生成图例。通过创建画布上下文,可以自由绘制图形和文字。
const canvas = document.getElementById('legendCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形图例
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 20, 20);
ctx.fillStyle = 'black';
ctx.font = '12px Arial';
ctx.fillText('数据系列1', 35, 25);
// 绘制圆形图例
ctx.beginPath();
ctx.arc(10, 50, 10, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.fillStyle = 'black';
ctx.fillText('数据系列2', 35, 55);
使用SVG创建图例
SVG是矢量图形标准,适合创建可缩放的图例。通过DOM操作可以动态添加图例元素。
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', '20');
rect.setAttribute('height', '20');
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
const text1 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text1.setAttribute('x', '35');
text1.setAttribute('y', '25');
text1.textContent = '数据系列3';
svg.appendChild(text1);
使用CSS和HTML构建图例
纯前端方案,利用CSS样式和HTML结构快速创建图例。
<div class="legend">
<div class="legend-item">
<div class="legend-color" style="background-color: orange;"></div>
<div class="legend-label">数据系列4</div>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: purple;"></div>
<div class="legend-label">数据系列5</div>
</div>
</div>
<style>
.legend {
display: flex;
flex-direction: column;
gap: 8px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-color {
width: 20px;
height: 20px;
}
.legend-label {
font-family: Arial;
font-size: 14px;
}
</style>
使用第三方库生成图例
借助Chart.js等可视化库可以快速生成专业图例。
import { Chart } from 'chart.js';
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['一月', '二月', '三月'],
datasets: [{
label: '销量',
data: [12, 19, 3],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
}]
},
options: {
plugins: {
legend: {
position: 'top',
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();
动态数据绑定图例
将图例与数据源绑定,实现数据变化时自动更新。

const dataSeries = [
{ color: '#FF6384', label: '产品A' },
{ color: '#36A2EB', label: '产品B' },
{ color: '#FFCE56', label: '产品C' }
];
function renderLegend(data) {
const container = document.getElementById('legendContainer');
container.innerHTML = '';
data.forEach(item => {
const div = document.createElement('div');
div.className = 'legend-item';
div.innerHTML = `
<span style="display:inline-block;width:20px;height:20px;background:${item.color}"></span>
<span>${item.label}</span>
`;
container.appendChild(div);
});
}
renderLegend(dataSeries);






