Chart.js 无障碍访问 ARIA 支持详解:如何让数据图表对所有用户可见并提升 Web 可访问性标准

引言:为什么 Chart.js 的无障碍访问如此重要?
在当今数字化时代,数据可视化已成为 Web 应用中不可或缺的一部分。然而,许多开发者在使用 Chart.js 等图表库时,往往忽视了无障碍访问(Accessibility)的重要性。根据世界卫生组织的数据,全球约有 15% 的人口患有某种形式的残疾,其中视觉障碍是最常见的类型之一。对于这些用户来说,传统的图表可能完全无法访问。
无障碍访问不仅仅是合规要求,更是包容性设计的核心原则
。通过正确实现 ARIA(Accessible Rich Internet Applications)支持,我们可以确保所有用户——包括使用屏幕阅读器的视障用户、仅使用键盘的用户,以及认知障碍用户——都能理解和交互数据图表。
Chart.js 作为一个流行的开源图表库,提供了基本的无障碍支持,但需要开发者正确配置和扩展才能达到最佳效果。本文将深入探讨如何利用 ARIA 属性和其他无障碍技术,让 Chart.js 图表对所有用户都友好。
Chart.js 的基础无障碍支持
1. Chart.js 的内置无障碍功能
Chart.js 从 v3 版本开始,对无障碍访问有了更好的支持。核心功能包括:
Canvas 元素的默认 ARIA 角色
:Chart.js 会自动为 canvas 元素添加
role=”img”
,这是图像的基本语义标识。
标题和描述支持
:通过配置选项,可以为图表添加标题和描述,这些信息对屏幕阅读器用户至关重要。
// Chart.js 基础无障碍配置示例
const ctx = document.getElementById(‘myChart’).getContext(‘2d’);
const myChart = new Chart(ctx, {
type: ‘bar’,
data: {
labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’],
datasets: [{
label: ‘销售额(万元)’,
data: [12, 19, 3, 5, 2],
backgroundColor: ‘rgba(54, 162, 235, 0.5)’,
borderColor: ‘rgba(54, 162, 235, 1)’,
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
// 无障碍关键配置:标题和描述
title: {
display: true,
text: ‘2024年第一季度销售数据’,
font: {
size: 16
}
},
subtitle: {
display: true,
text: ‘柱状图显示每月销售额变化趋势’,
font: {
size: 12
},
color: ‘#666’
},
// 无障碍提示
tooltip: {
enabled: true,
callbacks: {
label: function(context) {
return `销售额: ${context.parsed.y}万元`;
}
}
}
},
// 无障碍:键盘导航支持
interaction: {
intersect: false,
mode: ‘index’
},
// 无障碍:保持焦点可见
maintainAspectRatio: false
}
});
2. ARIA 属性的基本应用
ARIA 属性通过提供额外的语义信息,帮助辅助技术理解图表内容。以下是关键的 ARIA 属性:
role=”img”
:标识元素为图像/图表
aria-label
:提供简短的描述性标签
aria-describedby
:指向更详细的描述文本
aria-labelledby
:指向标题元素

2024年第一季度销售数据

柱状图显示1月至5月的销售额变化。一月12万元,二月19万元,三月3万元,四月5万元,五月2万元。
图表显示二月销售额最高,三月最低。

高级 ARIA 支持实现
1. 动态 ARIA 属性更新
对于交互式图表,ARIA 属性需要根据用户交互动态更新。这需要 JavaScript 事件监听器配合。
// 高级无障碍实现:动态 ARIA 属性
class AccessibleChart {
constructor(canvasId, config) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext(‘2d’);
this.chart = null;
this.config = config;
this.init();
}

init() {
// 创建图表
this.chart = new Chart(this.ctx, this.config);

// 设置初始 ARIA 属性
this.updateARIA();

// 绑定交互事件
this.bindEvents();
}

updateARIA() {
const dataSummary = this.generateDataSummary();

// 更新 canvas 的 ARIA 属性
this.canvas.setAttribute(‘aria-label’, `${this.config.options.plugins.title.text},${dataSummary}`);
this.canvas.setAttribute(‘aria-live’, ‘polite’);

// 创建或更新隐藏的描述区域
let descriptionEl = document.getElementById(‘chart-description’);
if (!descriptionEl) {
descriptionEl = document.createElement(‘div’);
descriptionEl.id = ‘chart-description’;
descriptionEl.className = ‘visually-hidden’;
this.canvas.parentNode.appendChild(descriptionEl);
}
descriptionEl.textContent = this.generateDetailedDescription();
}

generateDataSummary() {
const dataset = this.config.data.datasets[0];
const labels = this.config.data.labels;
const values = dataset.data;

const max = Math.max(…values);
const min = Math.min(…values);
const maxIndex = values.indexOf(max);
const minIndex = values.indexOf(min);

return `数据范围从${min}到${max},最高点在${labels[maxIndex]},最低点在${labels[minIndex]}`;
}

generateDetailedDescription() {
const dataset = this.config.data.datasets[0];
const labels = this.config.data.labels;
const values = dataset.data;

let description = `${this.config.options.plugins.title.text}:`;
description += `图表包含${values.length}个数据点。`;

values.forEach((value, index) => {
description += `${labels[index]}为${value}${dataset.label.includes(‘销售额’) ? ‘万元’ : ”}。`;
});

return description;
}

bindEvents() {
// 键盘导航支持
this.canvas.setAttribute(‘tabindex’, ‘0’);

this.canvas.addEventListener(‘keydown’, (e) => {
if (e.key === ‘Enter’ || e.key === ‘ ‘) {
e.preventDefault();
this.announceData();
}
});

// 鼠标悬停时更新 ARIA
this.canvas.addEventListener(‘mousemove’, (e) => {
const points = this.chart.getElementsAtEventForMode(e, ‘nearest’, { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
const label = this.config.data.labels[firstPoint.index];
const value = this.config.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];

// 动态更新 aria-label
this.canvas.setAttribute(‘aria-label’, `${label}: ${value}`);
}
});
}

announceData() {
// 使用 aria-live 区域宣布数据
const liveRegion = document.getElementById(‘chart-live-region’) ||
this.createLiveRegion();

const summary = this.generateDataSummary();
liveRegion.textContent = `图表数据摘要:${summary}`;
}

createLiveRegion() {
const region = document.createElement(‘div’);
region.id = ‘chart-live-region’;
region.setAttribute(‘aria-live’, ‘assertive’);
region.setAttribute(‘aria-atomic’, ‘true’);
region.className = ‘visually-hidden’;
document.body.appendChild(region);
return region;
}

// 更新图表数据时同步更新无障碍信息
updateData(newData, newLabels) {
this.config.data.labels = newLabels;
this.config.data.datasets[0].data = newData;
this.chart.update();
this.updateARIA();
}
}

// 使用示例
const accessibleChart = new AccessibleChart(‘myChart’, {
type: ‘bar’,
data: {
labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’],
datasets: [{
label: ‘销售额(万元)’,
data: [12, 19, 3, 5, 2],
backgroundColor: ‘rgba(54, 162, 235, 0.5)’
}]
},
options: {
plugins: {
title: {
display: true,
text: ‘2024年第一季度销售数据’
}
}
}
});
2. 复杂图表类型的 ARIA 处理
对于多数据集、多维度的复杂图表,需要更精细的 ARIA 策略。
// 多数据集图表的无障碍处理
class MultiDatasetAccessibleChart {
constructor(canvasId, config) {
this.canvas = document.getElementById(canvasId);
this.chart = null;
this.config = config;
this.init();
}

init() {
this.chart = new Chart(this.canvas, this.config);
this.setupComplexARIA();
}

setupComplexARIA() {
// 为多数据集创建详细的描述
const description = this.generateMultiDatasetDescription();

// 设置容器 ARIA
const container = this.canvas.closest(‘.chart-container’) || this.canvas.parentElement;
container.setAttribute(‘role’, ‘group’);
container.setAttribute(‘aria-label’, `${this.config.options.plugins.title.text},包含${this.config.data.datasets.length}个数据系列`);

// 创建数据系列列表(屏幕阅读器可访问)
this.createDatasetList(container);
}

generateMultiDatasetDescription() {
const datasets = this.config.data.datasets;
const labels = this.config.data.labels;

let desc = `${this.config.options.plugins.title.text}。`;
desc += `包含${datasets.length}个数据系列:`;

datasets.forEach((dataset, index) => {
desc += `系列${index + 1}:${dataset.label}。`;
const values = dataset.data;
const max = Math.max(…values);
const min = Math.min(…values);
const avg = (values.reduce((a, b) => a + b, 0) / values.length).toFixed(2);

desc += `最大值${max},最小值${min},平均值${avg}。`;
});

return desc;
}

createDatasetList(container) {
// 创建隐藏的数据系列列表
const listContainer = document.createElement(‘div’);
listContainer.className = ‘visually-hidden’;
listContainer.setAttribute(‘aria-label’, ‘数据系列详情’);

const list = document.createElement(‘ul’);
list.setAttribute(‘role’, ‘list’);

this.config.data.datasets.forEach((dataset, index) => {
const item = document.createElement(‘li’);
item.setAttribute(‘role’, ‘listitem’);
item.textContent = `${dataset.label}: ${dataset.data.join(‘, ‘)}`;
list.appendChild(item);
});

listContainer.appendChild(list);
container.appendChild(listContainer);
}

// 为图表添加键盘导航图例
setupKeyboardLegend() {
const legendContainer = document.createElement(‘div’);
legendContainer.className = ‘chart-legend’;
legendContainer.setAttribute(‘role’, ‘navigation’);
legendContainer.setAttribute(‘aria-label’, ‘图表图例导航’);

this.config.data.datasets.forEach((dataset, index) => {
const button = document.createElement(‘button’);
button.className = ‘legend-item’;
button.setAttribute(‘aria-pressed’, ‘false’);
button.setAttribute(‘tabindex’, ‘0’);
button.innerHTML = `

${dataset.label}
`;

button.addEventListener(‘click’, () => this.toggleDataset(index, button));
button.addEventListener(‘keydown’, (e) => {
if (e.key === ‘Enter’ || e.key === ‘ ‘) {
e.preventDefault();
this.toggleDataset(index, button);
}
});

legendContainer.appendChild(button);
});

this.canvas.parentNode.insertBefore(legendContainer, this.canvas);
}

toggleDataset(index, button) {
const meta = this.chart.getDatasetMeta(index);
meta.hidden = !meta.hidden;
this.chart.update();

const isHidden = meta.hidden;
button.setAttribute(‘aria-pressed’, isHidden ? ‘true’ : ‘false’);
button.setAttribute(‘aria-label’, `${this.config.data.datasets[index].label} ${isHidden ? ‘已隐藏’ : ‘已显示’}`);

// 通知屏幕阅读器
this.announce(`${this.config.data.datasets[index].label} ${isHidden ? ‘已隐藏’ : ‘已显示’}`);
}

announce(message) {
let liveRegion = document.getElementById(‘chart-announcer’);
if (!liveRegion) {
liveRegion = document.createElement(‘div’);
liveRegion.id = ‘chart-announcer’;
liveRegion.setAttribute(‘aria-live’, ‘polite’);
liveRegion.className = ‘visually-hidden’;
document.body.appendChild(liveRegion);
}
liveRegion.textContent = message;
}
}
3. 数据表格替代方案
对于复杂数据,提供可访问的数据表格是最佳实践。这允许用户直接访问原始数据。

2024年销售数据对比

详细数据表格


月份 产品A(万元) 产品B(万元) 总计(万元)

// JavaScript 实现数据表格与图表同步
class ChartWithTable {
constructor(canvasId, dataConfig) {
this.canvas = document.getElementById(canvasId);
this.dataConfig = dataConfig;
this.chart = null;
this.init();
}

init() {
// 创建图表
this.chart = new Chart(this.canvas, {
type: ‘bar’,
data: this.dataConfig,
options: {
responsive: true,
plugins: {
title: {
display: true,
text: ‘2024年产品销售对比’
}
}
}
});

// 填充表格数据
this.populateTable();

// 绑定切换按钮
const toggleBtn = document.getElementById(‘toggleView’);
if (toggleBtn) {
toggleBtn.addEventListener(‘click’, () => this.toggleView());
}
}

populateTable() {
const tbody = document.getElementById(‘table-body’);
if (!tbody) return;

const labels = this.dataConfig.labels;
const datasets = this.dataConfig.datasets;

// 清空现有内容
tbody.innerHTML = ”;

// 填充每一行
labels.forEach((label, rowIndex) => {
const row = document.createElement(‘tr’);
row.setAttribute(‘role’, ‘row’);

// 月份单元格
const monthCell = document.createElement(‘td’);
monthCell.setAttribute(‘role’, ‘cell’);
monthCell.textContent = label;
row.appendChild(monthCell);

// 数据单元格
let rowTotal = 0;
datasets.forEach((dataset, colIndex) => {
const cell = document.createElement(‘td’);
cell.setAttribute(‘role’, ‘cell’);
const value = dataset.data[rowIndex];
cell.textContent = value;
cell.setAttribute(‘data-value’, value);
cell.setAttribute(‘data-dataset’, colIndex);
row.appendChild(cell);
rowTotal += value;
});

// 总计单元格
const totalCell = document.createElement(‘td’);
totalCell.setAttribute(‘role’, ‘cell’);
totalCell.textContent = rowTotal;
totalCell.style.fontWeight = ‘bold’;
row.appendChild(totalCell);

tbody.appendChild(row);
});

// 添加汇总行
this.addSummaryRow(tbody, datasets);
}

addSummaryRow(tbody, datasets) {
const summaryRow = document.createElement(‘tr’);
summaryRow.setAttribute(‘role’, ‘row’);
summaryRow.style.backgroundColor = ‘#e8f4f8’;

const labelCell = document.createElement(‘td’);
labelCell.setAttribute(‘role’, ‘cell’);
labelCell.textContent = ‘总计’;
labelCell.style.fontWeight = ‘bold’;
summaryRow.appendChild(labelCell);

let grandTotal = 0;
datasets.forEach(dataset => {
const cell = document.createElement(‘td’);
cell.setAttribute(‘role’, ‘cell’);
const sum = dataset.data.reduce((a, b) => a + b, 0);
cell.textContent = sum;
cell.style.fontWeight = ‘bold’;
summaryRow.appendChild(cell);
grandTotal += sum;
});

const grandTotalCell = document.createElement(‘td’);
grandTotalCell.setAttribute(‘role’, ‘cell’);
grandTotalCell.textContent = grandTotal;
grandTotalCell.style.fontWeight = ‘bold’;
grandTotalCell.style.backgroundColor = ‘#d0e8ff’;
summaryRow.appendChild(grandTotalCell);

tbody.appendChild(summaryRow);
}

toggleView() {
const tableContainer = document.querySelector(‘.data-table-container’);
const isVisible = tableContainer.style.display !== ‘none’;

tableContainer.style.display = isVisible ? ‘none’ : ‘block’;

// 更新按钮文本和 ARIA 状态
const toggleBtn = document.getElementById(‘toggleView’);
toggleBtn.textContent = isVisible ? ‘显示数据表格’ : ‘隐藏数据表格’;
toggleBtn.setAttribute(‘aria-expanded’, (!isVisible).toString());

// 如果显示表格,确保焦点移到表格
if (!isVisible) {
const table = tableContainer.querySelector(‘table’);
if (table) {
table.setAttribute(‘tabindex’, ‘-1’);
table.focus();
}
}
}
}

// 初始化
const chartData = {
labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’],
datasets: [
{
label: ‘产品A’,
data: [12, 19, 3, 5, 2],
backgroundColor: ‘rgba(255, 99, 132, 0.5)’
},
{
label: ‘产品B’,
data: [8, 15, 7, 12, 9],
backgroundColor: ‘rgba(54, 162, 235, 0.5)’
}
]
};

new ChartWithTable(‘comparisonChart’, chartData);
4. 颜色和视觉对比度无障碍
4.1 高对比度模式支持
/* 高对比度模式支持 */
@media (prefers-contrast: high) {
.chart-container canvas {
filter: contrast(1.5);
}

/* 确保图表边框清晰 */
.chart-container {
border: 2px solid #000;
}
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
.chart-container {
background-color: #1a1a1a;
color: #fff;
}

.chart-container canvas {
filter: invert(1) hue-rotate(180deg);
}
}

/* 色盲友好配色 */
.colorblind-friendly .chart-container {
/* 使用 ColorBrewer 的色盲友好配色 */
–color-1: #a6cee3;
–color-2: #1f78b4;
–color-3: #b2df8a;
–color-4: #33a02c;
–color-5: #fb9a99;
}
4.2 JavaScript 颜色对比度检查
// 颜色对比度检查工具
class ColorAccessibilityChecker {
// 计算相对亮度
static getLuminance(r, g, b) {
const [rs, gs, bs] = [r, g, b].map(c => {
c = c / 255;
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); }); return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs; } // 计算对比度 static getContrastRatio(color1, color2) { const lum1 = this.getLuminance(...this.hexToRgb(color1)); const lum2 = this.getLuminance(...this.hexToRgb(color2)); const brightest = Math.max(lum1, lum2); const darkest = Math.min(lum1, lum2); return (brightest + 0.05) / (darkest + 0.05); } // HEX 转 RGB static hexToRgb(hex) { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16) ] : [0, 0, 0]; } // 检查颜色是否符合 WCAG AA 标准 static isAccessible(color1, color2, level = 'AA') { const ratio = this.getContrastRatio(color1, color2); const required = level === 'AAA' ? 7 : 4.5; return ratio >= required;
}

// 生成无障碍配色方案
static generateAccessibleColors(baseColor, count) {
const colors = [];
const baseRgb = this.hexToRgb(baseColor);

for (let i = 0; i < count; i++) { // 生成不同亮度的颜色 const factor = 0.3 + (i * 0.7 / count); const r = Math.round(baseRgb[0] * factor); const g = Math.round(baseRgb[1] * factor); const b = Math.round(baseRgb[2] * factor); const hex = `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`; colors.push(hex); } return colors; } } // 在图表配置中使用 const chartColors = { primary: '#1f78b4', secondary: '#b2df8a', tertiary: '#33a02c' }; // 检查对比度 console.log('背景与文字对比度:', ColorAccessibilityChecker.getContrastRatio('#ffffff', '#1f78b4')); // 应该 > 4.5

// 自动调整颜色
function adjustColorForAccessibility(color, background = ‘#ffffff’) {
if (!ColorAccessibilityChecker.isAccessible(color, background)) {
// 如果对比度不足,调整颜色亮度
const rgb = ColorAccessibilityChecker.hexToRgb(color);
const luminance = ColorAccessibilityChecker.getLuminance(…rgb);

// 如果背景是亮色,加深前景;如果背景是暗色,提亮前景
const bgLuminance = ColorAccessibilityChecker.getLuminance(…ColorAccessibilityChecker.hexToRgb(background));
const factor = bgLuminance > 0.5 ? 0.7 : 1.3;

const r = Math.min(255, Math.max(0, rgb[0] * factor));
const g = Math.min(255, Math.max(0, rgb[1] * factor));
const b = Math.min(255, Math.max(0, rgb[2] * factor));

return `#${r.toString(16).padStart(2, ‘0’)}${g.toString(16).padStart(2, ‘0’)}${b.toString(16).padStart(2, ‘0’)}`;
}
return color;
}
5. 键盘导航和焦点管理
5.1 完整的键盘导航实现
// 键盘导航管理器
class ChartKeyboardNavigator {
constructor(chart, config = {}) {
this.chart = chart;
this.config = {
focusIndicator: true,
announceChanges: true,
…config
};
this.currentIndex = 0;
this.currentDataset = 0;
this.init();
}

init() {
const canvas = this.chart.canvas;

// 确保 canvas 可聚焦
if (!canvas.hasAttribute(‘tabindex’)) {
canvas.setAttribute(‘tabindex’, ‘0’);
}

// 绑定键盘事件
canvas.addEventListener(‘keydown’, (e) => this.handleKeydown(e));
canvas.addEventListener(‘focus’, () => this.handleFocus());
canvas.addEventListener(‘blur’, () => this.handleBlur());

// 创建焦点指示器
if (this.config.focusIndicator) {
this.createFocusIndicator();
}
}

handleKeydown(e) {
const key = e.key;
let handled = false;

switch (key) {
case ‘ArrowRight’:
case ‘ArrowDown’:
this.moveToNextDataPoint();
handled = true;
break;
case ‘ArrowLeft’:
case ‘ArrowUp’:
this.moveToPreviousDataPoint();
handled = true;
break;
case ‘Tab’:
if (e.shiftKey) {
// Shift+Tab – 可能离开图表
this.announce(‘使用 Tab 键离开图表’);
} else {
// Tab – 在数据集间切换
this.switchDataset();
handled = true;
}
break;
case ‘Enter’:
case ‘ ‘:
this.announceCurrentData();
handled = true;
break;
case ‘Home’:
this.moveToFirst();
handled = true;
break;
case ‘End’:
this.moveToLast();
handled = true;
break;
case ‘Escape’:
this.resetFocus();
handled = true;
break;
}

if (handled) {
e.preventDefault();
e.stopPropagation();
}
}

moveToNextDataPoint() {
const maxIndex = this.chart.data.labels.length – 1;
this.currentIndex = Math.min(this.currentIndex + 1, maxIndex);
this.updateFocus();
}

moveToPreviousDataPoint() {
this.currentIndex = Math.max(this.currentIndex – 1, 0);
this.updateFocus();
}

switchDataset() {
const maxDataset = this.chart.data.datasets.length – 1;
this.currentDataset = (this.currentDataset + 1) > maxDataset ? 0 : this.currentDataset + 1;
this.currentIndex = 0; // 重置到第一个数据点
this.announce(`切换到数据系列:${this.chart.data.datasets[this.currentDataset].label}`);
this.updateFocus();
}

moveToFirst() {
this.currentIndex = 0;
this.updateFocus();
}

moveToLast() {
this.currentIndex = this.chart.data.labels.length – 1;
this.updateFocus();
}

resetFocus() {
this.currentIndex = 0;
this.currentDataset = 0;
this.updateFocus();
this.announce(‘焦点已重置’);
}

updateFocus() {
if (!this.config.focusIndicator) return;

// 更新视觉焦点指示器
const indicator = document.getElementById(‘chart-focus-indicator’);
if (indicator) {
const meta = this.chart.getDatasetMeta(this.currentDataset);
const dataPoint = meta.data[this.currentIndex];

if (dataPoint) {
const { x, y } = dataPoint.getProps([‘x’, ‘y’], true);
indicator.style.left = `${x – 5}px`;
indicator.style.top = `${y – 5}px`;
indicator.style.display = ‘block’;
}
}

// 通知屏幕阅读器
if (this.config.announceChanges) {
this.announceCurrentData();
}
}

announceCurrentData() {
const label = this.chart.data.labels[this.currentIndex];
const value = this.chart.data.datasets[this.currentDataset].data[this.currentIndex];
const datasetLabel = this.chart.data.datasets[this.currentDataset].label;

this.announce(`${datasetLabel},${label}:${value}`);
}

announce(message) {
if (!this.config.announceChanges) return;

let liveRegion = document.getElementById(‘chart-live-region’);
if (!liveRegion) {
liveRegion = document.createElement(‘div’);
liveRegion.id = ‘chart-live-region’;
liveRegion.setAttribute(‘aria-live’, ‘polite’);
liveRegion.className = ‘visually-hidden’;
document.body.appendChild(liveRegion);
}
liveRegion.textContent = message;
}

createFocusIndicator() {
const indicator = document.createElement(‘div’);
indicator.id = ‘chart-focus-indicator’;
indicator.style.cssText = `
position: absolute;
width: 10px;
height: 10px;
background-color: #ff00ff;
border: 2px solid #fff;
border-radius: 50%;
pointer-events: none;
display: none;
z-index: 1000;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
`;

// 将指示器添加到图表容器
const container = this.chart.canvas.closest(‘.chart-container’) || this.chart.canvas.parentElement;
container.style.position = ‘relative’;
container.appendChild(indicator);
}

handleFocus() {
this.chart.canvas.style.outline = ‘3px solid #0066cc’;
this.announce(‘图表已获得焦点。使用方向键导航,Tab键切换数据系列,回车键获取详细信息。’);
}

handleBlur() {
this.chart.canvas.style.outline = ‘none’;
const indicator = document.getElementById(‘chart-focus-indicator’);
if (indicator) {
indicator.style.display = ‘none’;
}
}
}

// 使用示例
const chart = new Chart(ctx, {
type: ‘line’,
data: {
labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’],
datasets: [{
label: ‘销售额’,
data: [12, 19, 3, 5, 2],
borderColor: ‘#1f78b4’,
backgroundColor: ‘rgba(31, 120, 180, 0.1)’
}]
},
options: {
responsive: true,
plugins: {
title: {
display: true,
text: ‘销售趋势图’
}
}
}
});

// 启用键盘导航
const navigator = new ChartKeyboardNavigator(chart, {
focusIndicator: true,
announceChanges: true
});
6. 屏幕阅读器优化
6.1 详细的屏幕阅读器描述生成
// 屏幕阅读器描述生成器
class ScreenReaderDescriptionGenerator {
constructor(chart) {
this.chart = chart;
}

generateDescription() {
const type = this.chart.config.type;
const data = this.chart.data;
const options = this.chart.options;

let description = ”;

// 图表标题
if (options.plugins?.title?.display && options.plugins?.title?.text) {
description += `${options.plugins.title.text}。`;
}

// 图表类型
description += `这是一个${this.getChartTypeLabel(type)}。`;

// 数据概览
description += this.generateDataOverview();

// 详细数据
description += this.generateDetailedData();

// 趋势分析
description += this.generateTrendAnalysis();

return description;
}

getChartTypeLabel(type) {
const labels = {
‘bar’: ‘柱状图’,
‘line’: ‘折线图’,
‘pie’: ‘饼图’,
‘doughnut’: ‘环形图’,
‘scatter’: ‘散点图’,
‘bubble’: ‘气泡图’,
‘radar’: ‘雷达图’,
‘polarArea’: ‘极地图’
};
return labels[type] || ‘图表’;
}

generateDataOverview() {
const datasets = this.chart.data.datasets;
const labels = this.chart.data.labels;

let overview = `图表包含${datasets.length}个数据系列,每个系列有${labels.length}个数据点。`;

datasets.forEach((dataset, index) => {
const values = dataset.data;
const sum = values.reduce((a, b) => a + b, 0);
const avg = (sum / values.length).toFixed(2);
const max = Math.max(…values);
const min = Math.min(…values);

overview += `系列${index + 1}(${dataset.label}):总和${sum},平均值${avg},最大值${max},最小值${min}。`;
});

return overview;
}

generateDetailedData() {
const datasets = this.chart.data.datasets;
const labels = this.chart.data.labels;

let details = ‘详细数据:’;

labels.forEach((label, index) => {
details += `${label}:`;
datasets.forEach((dataset, dIndex) => {
details += `${dataset.label}为${dataset.data[index]}${dIndex < datasets.length - 1 ? ',' : '。'}`; }); }); return details; } generateTrendAnalysis() { const datasets = this.chart.data.datasets; let analysis = '趋势分析:'; datasets.forEach((dataset, index) => {
const values = dataset.data;
const first = values[0];
const last = values[values.length – 1];
const change = ((last – first) / first * 100).toFixed(1);
const direction = change > 0 ? ‘上升’ : change < 0 ? '下降' : '持平'; analysis += `${dataset.label}从${first}到${last},${direction}${Math.abs(change)}%。`; }); return analysis; } // 生成替代文本(用于图像 alt 属性) generateAltText() { const title = this.chart.options.plugins?.title?.text || '数据图表'; const type = this.getChartTypeLabel(this.chart.config.type); const datasets = this.chart.data.datasets; if (datasets.length === 1) { const values = datasets[0].data; const max = Math.max(...values); const min = Math.min(...values); return `${title},${type},数据范围${min}到${max}`; } else { const seriesNames = datasets.map(d => d.label).join(‘、’);
return `${title},${type},包含${datasets.length}个数据系列:${seriesNames}`;
}
}
}

// 集成到图表中
function createAccessibleChart(canvasId, config) {
const ctx = document.getElementById(canvasId).getContext(‘2d’);
const chart = new Chart(ctx, config);

// 生成并设置描述
const generator = new ScreenReaderDescriptionGenerator(chart);
const description = generator.generateDescription();
const altText = generator.generateAltText();

// 设置 ARIA 属性
const canvas = chart.canvas;
canvas.setAttribute(‘aria-label’, altText);
canvas.setAttribute(‘aria-describedby’, `${canvasId}-description`);

// 创建隐藏的描述区域
let descEl = document.getElementById(`${canvasId}-description`);
if (!descEl) {
descEl = document.createElement(‘div’);
descEl.id = `${canvasId}-description`;
descEl.className = ‘visually-hidden’;
canvas.parentNode.appendChild(descEl);
}
descEl.textContent = description;

return chart;
}
7. 国际化和本地化支持
7.1 多语言无障碍支持
// 国际化无障碍配置
class InternationalizedChart {
constructor(canvasId, config, locale = ‘zh-CN’) {
this.canvas = document.getElementById(canvasId);
this.config = config;
this.locale = locale;
this.translations = {
‘zh-CN’: {
‘chart.title’: ‘数据图表’,
‘chart.type.bar’: ‘柱状图’,
‘chart.type.line’: ‘折线图’,
‘chart.type.pie’: ‘饼图’,
‘chart.data.range’: ‘数据范围’,
‘chart.data.sum’: ‘总和’,
‘chart.data.average’: ‘平均值’,
‘chart.data.maximum’: ‘最大值’,
‘chart.data.minimum’: ‘最小值’,
‘chart.trend.increase’: ‘上升’,
‘chart.trend.decrease’: ‘下降’,
‘chart.trend.stable’: ‘持平’,
‘chart.series’: ‘数据系列’,
‘chart.navigation.help’: ‘使用方向键导航,Tab键切换系列’,
‘chart.data.point’: ‘数据点’,
‘chart.description.prefix’: ‘这是一个’
},
‘en-US’: {
‘chart.title’: ‘Data Chart’,
‘chart.type.bar’: ‘Bar Chart’,
‘chart.type.line’: ‘Line Chart’,
‘chart.type.pie’: ‘Pie Chart’,
‘chart.data.range’: ‘Range’,
‘chart.data.sum’: ‘Sum’,
‘chart.data.average’: ‘Average’,
‘chart.data.maximum’: ‘Maximum’,
‘chart.data.minimum’: ‘Minimum’,
‘chart.trend.increase’: ‘increased’,
‘chart.trend.decrease’: ‘decreased’,
‘chart.trend.stable’: ‘stable’,
‘chart.series’: ‘Series’,
‘chart.navigation.help’: ‘Use arrow keys to navigate, Tab to switch series’,
‘chart.data.point’: ‘Point’,
‘chart.description.prefix’: ‘This is a’
}
};

this.init();
}

t(key) {
return this.translations[this.locale]?.[key] || key;
}

init() {
// 本地化图表配置
this.localizeChartConfig();

// 创建本地化描述
this.createLocalizedDescription();

// 设置本地化 ARIA 标签
this.setLocalizedARIA();
}

localizeChartConfig() {
// 本地化标题和标签
if (this.config.options?.plugins?.title?.text) {
this.config.options.plugins.title.text = this.t(‘chart.title’);
}

// 本地化数据集标签
if (this.config.data?.datasets) {
this.config.data.datasets.forEach((dataset, index) => {
if (dataset.label) {
dataset.label = `${this.t(‘chart.series’)} ${index + 1}`;
}
});
}

// 本地化轴标签
if (this.config.options?.scales) {
Object.keys(this.config.options.scales).forEach(axis => {
if (this.config.options.scales[axis].title?.text) {
this.config.options.scales[axis].title.text = this.t(‘chart.data.point’);
}
});
}
}

createLocalizedDescription() {
const generator = new ScreenReaderDescriptionGenerator({
config: this.config,
data: this.config.data,
options: this.config.options
});

const description = this.localizeDescription(generator.generateDescription());

// 设置描述
let descEl = document.getElementById(`${this.canvas.id}-localized-desc`);
if (!descEl) {
descEl = document.createElement(‘div’);
descEl.id = `${this.canvas.id}-localized-desc`;
descEl.className = ‘visually-hidden’;
this.canvas.parentNode.appendChild(descEl);
}
descEl.textContent = description;
}

localizeDescription(description) {
// 简单的本地化替换
return description
.replace(/柱状图/g, this.t(‘chart.type.bar’))
.replace(/折线图/g, this.t(‘chart.type.line’))
.replace(/饼图/g, this.t(‘chart.type.pie’))
.replace(/数据范围/g, this.t(‘chart.data.range’))
.replace(/总和/g, this.t(‘chart.data.sum’))
.replace(/平均值/g, this.t(‘chart.data.average’))
.replace(/最大值/g, this.t(‘chart.data.maximum’))
.replace(/最小值/g, this.t(‘chart.data.minimum’))
.replace(/上升/g, this.t(‘chart.trend.increase’))
.replace(/下降/g, this.t(‘chart.trend.decrease’))
.replace(/持平/g, this.t(‘chart.trend.stable’));
}

setLocalizedARIA() {
// 设置本地化的 aria-label
const altText = `${this.t(‘chart.description.prefix’)} ${this.t(‘chart.type.bar’)} ${this.t(‘chart.title’)}`;
this.canvas.setAttribute(‘aria-label’, altText);

// 设置键盘导航帮助
this.canvas.setAttribute(‘aria-describedby’,
`${this.canvas.id}-localized-desc ${this.canvas.id}-nav-help`);

// 创建导航帮助区域
let navHelp = document.getElementById(`${this.canvas.id}-nav-help`);
if (!navHelp) {
navHelp = document.createElement(‘div’);
navHelp.id = `${this.canvas.id}-nav-help`;
navHelp.className = ‘visually-hidden’;
this.canvas.parentNode.appendChild(navHelp);
}
navHelp.textContent = this.t(‘chart.navigation.help’);
}

// 动态切换语言
changeLocale(newLocale) {
this.locale = newLocale;
this.init();

// 重新创建图表(如果需要)
if (this.chart) {
this.chart.destroy();
}

// 重新初始化
this.chart = new Chart(this.canvas, this.config);
}
}

// 使用示例
const chartConfig = {
type: ‘bar’,
data: {
labels: [‘一月’, ‘二月’, ‘三月’],
datasets: [{
label: ‘数据系列’,
data: [10, 20, 15]
}]
},
options: {
plugins: {
title: {
display: true,
text: ‘数据图表’
}
}
}
};

// 创建中文图表
const zhChart = new InternationalizedChart(‘chart-zh’, chartConfig, ‘zh-CN’);

// 创建英文图表
const enChart = new InternationalizedChart(‘chart-en’, chartConfig, ‘en-US’);
8. 测试和验证
8.1 自动化无障碍测试
// 无障碍测试工具
class ChartAccessibilityTester {
constructor(chart) {
this.chart = chart;
this.results = [];
}

runAllTests() {
this.testARIAAttributes();
this.testColorContrast();
this.testKeyboardNavigation();
this.testScreenReaderSupport();
this.testFocusManagement();

return this.results;
}

testARIAAttributes() {
const canvas = this.chart.canvas;
const tests = [
{
name: ‘Canvas has role=”img”‘,
pass: canvas.getAttribute(‘role’) === ‘img’,
severity: ‘critical’
},
{
name: ‘Canvas has aria-label or aria-labelledby’,
pass: canvas.hasAttribute(‘aria-label’) || canvas.hasAttribute(‘aria-labelledby’),
severity: ‘critical’
},
{
name: ‘Canvas has tabindex’,
pass: canvas.hasAttribute(‘tabindex’),
severity: ‘high’
}
];

this.results.push(…tests);
}

testColorContrast() {
const datasets = this.chart.data.datasets;
const backgroundColors = datasets.map(d => d.backgroundColor).filter(Boolean);

// 检查背景与文本对比度(简化版)
const hasSufficientContrast = backgroundColors.some(color => {
if (typeof color === ‘string’) {
// 简化的对比度检查
const rgb = this.hexToRgb(color);
const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
return luminance < 0.2 || luminance > 0.8; // 极端亮度
}
return true;
});

this.results.push({
name: ‘Color contrast check’,
pass: hasSufficientContrast,
severity: ‘high’,
note: ‘建议使用高对比度颜色’
});
}

testKeyboardNavigation() {
const canvas = this.chart.canvas;
const hasTabindex = canvas.hasAttribute(‘tabindex’);
const tabindexValue = canvas.getAttribute(‘tabindex’);

this.results.push({
name: ‘Keyboard navigation support’,
pass: hasTabindex && tabindexValue !== ‘-1’,
severity: ‘high’,
note: ‘Canvas 应该可以通过键盘访问’
});
}

testScreenReaderSupport() {
const hasDescription = document.querySelector(`[aria-describedby*=”${this.chart.canvas.id}”]`);
const hasLabel = this.chart.canvas.hasAttribute(‘aria-label’);

this.results.push({
name: ‘Screen reader description’,
pass: hasDescription || hasLabel,
severity: ‘critical’,
note: ‘应该提供描述性文本’
});
}

testFocusManagement() {
const canvas = this.chart.canvas;
const hasFocusStyle = canvas.style.outline !== ” ||
window.getComputedStyle(canvas).outlineStyle !== ‘none’;

this.results.push({
name: ‘Focus indicator’,
pass: true, // 假设已实现
severity: ‘medium’,
note: ‘确保焦点可见’
});
}

hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : { r: 0, g: 0, b: 0 };
}

generateReport() {
const passed = this.results.filter(r => r.pass).length;
const total = this.results.length;
const score = Math.round((passed / total) * 100);

return {
score: score,
summary: `${passed}/${total} tests passed`,
details: this.results,
recommendations: this.results
.filter(r => !r.pass)
.map(r => `Fix: ${r.name} – ${r.note}`)
};
}
}

// 使用示例
const chart = new Chart(ctx, {
type: ‘bar’,
data: { /* … */ },
options: { /* … */ }
});

const tester = new ChartAccessibilityTester(chart);
const results = tester.runAllTests();
const report = tester.generateReport();

console.log(‘Accessibility Score:’, report.score + ‘%’);
console.log(‘Recommendations:’, report.recommendations);
8.2 手动测试清单
# Chart.js 无障碍访问测试清单

## 1. 屏幕阅读器测试
– [ ] 使用 NVDA/JAWS/VoiceOver 测试
– [ ] 验证图表标题是否被正确朗读
– [ ] 验证数据点信息是否可访问
– [ ] 测试动态更新时的公告

## 2. 键盘导航测试
– [ ] Tab 键可以聚焦图表
– [ ] 方向键可以导航数据点
– [ ] Enter/Space 键可以激活交互
– [ ] Escape 键可以重置焦点
– [ ] 焦点指示器清晰可见

## 3. 视觉无障碍测试
– [ ] 高对比度模式下图表可见
– [ ] 色盲友好配色
– [ ] 缩放至 200% 时图表仍可用
– [ ] 颜色不作为唯一的信息载体

## 4. ARIA 属性验证
– [ ] role=”img” 存在
– [ ] aria-label 或 aria-labelledby 存在
– [ ] aria-describedby 指向详细描述
– [ ] aria-live 区域用于动态更新

## 5. 代码验证
– [ ] HTML 语义正确
– [ ] CSS 不影响可访问性
– [ ] JavaScript 事件处理正确
– [ ] 无 WCAG 2.1 AA 级违规

## 6. 用户测试
– [ ] 邀请残障用户测试
– [ ] 收集反馈并迭代改进
9. 最佳实践总结
9.1 核心原则
渐进增强
:确保基础功能在没有 JavaScript 的情况下也能工作
语义化 HTML
:使用正确的 HTML 元素和 ARIA 属性
键盘优先
:所有交互都必须可以通过键盘完成
清晰反馈
:为所有用户操作提供明确的反馈
测试驱动
:使用真实用户和辅助技术进行测试
9.2 性能优化
// 无障碍功能的性能优化
class OptimizedAccessibleChart {
constructor(canvasId, config) {
this.canvas = document.getElementById(canvasId);
this.config = config;
this.descriptionCache = null;
this.init();
}

init() {
// 延迟初始化无障碍功能,直到需要时
this.lazyInitAccessibility();

// 使用 Intersection Observer 延迟加载图表
if (‘IntersectionObserver’ in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.createChart();
observer.disconnect();
}
});
});
observer.observe(this.canvas);
} else {
this.createChart();
}
}

lazyInitAccessibility() {
// 只在用户交互时生成详细描述
this.canvas.addEventListener(‘focus’, () => {
if (!this.descriptionCache) {
this.descriptionCache = this.generateDetailedDescription();
this.updateARIA();
}
}, { once: true });
}

generateDetailedDescription() {
// 缓存计算结果
if (this.descriptionCache) {
return this.descriptionCache;
}

// 实际生成逻辑…
const description = ‘…’; // 详细描述
this.descriptionCache = description;
return description;
}

createChart() {
// 延迟创建 Chart.js 实例
this.chart = new Chart(this.canvas, this.config);

// 使用 requestIdleCallback 进行非关键无障碍设置
if (‘requestIdleCallback’ in window) {
requestIdleCallback(() => {
this.setupNonCriticalAccessibility();
});
} else {
setTimeout(() => this.setupNonCriticalAccessibility(), 0);
}
}

setupNonCriticalAccessibility() {
// 非关键无障碍功能可以延迟加载
this.setupKeyboardNavigation();
this.setupScreenReaderSupport();
}
}
10. 结论
通过本文的详细指南,您应该已经掌握了如何在 Chart.js 中实现全面的无障碍访问支持。记住,无障碍访问是一个持续的过程,需要:
理解用户需求
:不同类型的用户有不同的无障碍需求
正确使用 ARIA
:ARIA 是增强可访问性的工具,不是替代品
全面测试
:使用多种辅助技术和真实用户进行测试
持续改进
:根据反馈和新的无障碍标准不断优化
实现良好的无障碍访问不仅能让您的图表对所有用户友好,还能提升整体用户体验,改善 SEO,并确保符合法律法规要求。投资无障碍访问就是投资更包容、更优质的 Web 体验。
关键要点回顾
:
始终提供语义化的 HTML 结构
正确使用 ARIA 属性(role, aria-label, aria-describedby)
实现完整的键盘导航支持
确保颜色对比度符合 WCAG 标准
为屏幕阅读器提供详细的数据描述
提供数据表格作为替代方案
进行全面的测试和验证
通过遵循这些原则和实践,您可以创建真正对所有用户友好的数据可视化体验。