a11y
上一篇
lottie
下一篇
按需打包
Loading...
由于画布通常呈现为一个“黑盒”,其中的内容无法被文本化进而被 Screen Reader 朗读。针对不同类型的障碍人士,可以提供例如文本提取、键盘导航等功能。
在图表领域做的最好的是 highcharts,其中有大量实践值得借鉴。
在 G2 中可以借助插件实现 文本搜索 的功能。
首先安装 @antv/g-plugin-a11y:
npm install @antv/g-plugin-rough-canvas-renderer --save
然后在插件列表中引入:
import { Plugin } from '@antv/g-plugin-a11y';const plugin = new Plugin({ enableExtractingText: true });const chart = new Chart({container: 'container',plugins: [plugin],});
在一些渲染器(例如 g-canvas / g-webgl / g-canvaskit中,当文本被绘制后便无法使用浏览器自带的搜索功能(Command + F
)定位匹配,同样对于 SEO 也不友好。
在该示例中,我们开启 enableExtractingText
后便可以使用文本搜索的功能:
import { Chart } from '@antv/g2';const plugin = new gPluginA11y.Plugin({ enableExtractingText: true });const labelFormatter = (d) => Math.abs(d) + (d < 0 ? 'BC' : d > 0 ? 'AC' : '');const left = (d) => d.end > -1500 && d.start > -3000;const chart = new Chart({container: 'container',width: 900,height: 1000,plugins: [plugin],});chart.options({type: 'interval',width: 900,height: 1000,data: {type: 'fetch',value: 'https://assets.antv.antgroup.com/g2/world-history.json',},encode: { x: 'civilization', y: ['start', 'end'], color: 'region' },transform: [{ type: 'sortX', by: 'y' },{ type: 'sortColor', by: 'y', reducer: 'min' },],scale: { color: { palette: 'set2' } },coordinate: { transform: [{ type: 'transpose' }] },axis: { x: false },labels: [{text: 'civilization',position: (d) => (left(d) ? 'left' : 'right'),textAlign: (d) => (left(d) ? 'end' : 'start'),dx: (d) => (left(d) ? -5 : 5),fontSize: 10,},],tooltip: {items: [{name: 'start',field: 'start',valueFormatter: labelFormatter,},{name: 'end',field: 'end',valueFormatter: labelFormatter,},],},});chart.render();
在实现中我们在画布容器内添加了 DOM 元素,用于与画布中的可见文本实时同步:
<divid="g-a11y-text-extractor-mask"style="position: absolute; inset: 0px; z-index: 99; pointer-events: none; user-select: none; overflow: hidden;"><divid="g-a11y-text-extractor-text-507"style="line-height: 1; position: absolute; white-space: pre; word-break: keep-all; color: transparent !important; font-family: sans-serif; font-size: 12px; transform-origin: 0px 0px; transform: translate(0px, 0px) translate(0px, -50%) matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 215.856, 24, 0, 1);">East Asia</div></div>
有以下注意事项:
<foreignObject>
,不会添加上述 DOM 内容12px
),因此太小的文本会有不一致的渲染效果