设置纹理
上一篇
按需打包
下一篇
绘制 3D 图表
Loading...
相比单调的填充色,使用纹理填充能丰富表现力,在无障碍和黑白打印场景下也有不错的应用。为此我们提供了以下三种方式,按使用成本从简到难依次为:
我们在 g-pattern 中内置了常见的三种纹理,通过参数可以便捷地调整外观,这也是最简单的一种纹理使用方式:
使用方式如下,首先安装依赖:
$ npm install @antv/g-pattern --save;
然后就可以使用其中的内置纹理了。在该示例中:
import { lines } from '@antv/g-pattern';chart//... 省略其它命令式调用.style('fill', (_, idx) => {return {image: lines({backgroundColor: colors[idx],backgroundOpacity: 0.65,stroke: colors[idx],lineWidth: 4,spacing: 5,}),repetition: 'repeat',transform: 'rotate(30)',};});
效果如下:
更多参数含义及其效果详见 完整 g-pattern API。
当上述内置纹理不满足需求时,可以使用 G API 自定义,就像描述场景一样。
在该示例中,我们首先从上下文中获取 document 对象,通过 document.createElement 创建了一个 Rect 和 Path,把它们作为纹理来源:
mark.style('fill', ({ value }) => {const { document } = chart.getContext().canvas;const background = document.createElement('rect', {style: {width,height,fill: color,},});const line = document.createElement('path', {style: {d: `M 0 ${-height} L ${width * 2} ${height}M ${-width} ${-height} L ${width} ${height}M ${-width} 0 L ${width} ${height * 2}`,stroke,lineWidth: 1,strokeOpacity: 0.9,},});background.appendChild(line);return {image: background,repetition: 'repeat',};});
效果如下:
更多用法可参考 G API。
可以参考 G API,其它可用的纹理来源包括:
'http://example.png'
其中图片 URL、HTMLImageElement、HTMLVideoElement 都是静态资源,而 HTMLCanvasElement 可用于程序化生成纹理,效果如下:
在该示例中,我们使用了 HTMLCanvasElement
配合 Canvas API 自定义:
// 程序化生成const canvas = createCanvas(width, height);const ctx = canvas.getContext('2d');drawRect(ctx, width, height, color);drawLinePattern(ctx, stroke, width, height, cross);// 使用chart.style('fill', ({ value }) => {return { image: canvas, repetition: 'repeat' };});
不难看出,此种程序化生成方式需要使用者对于 Canvas API 有很深的理解,当然它也拥有最高的自由度。