Loading...
Compared with monotonous fill colors, using pattern fills can enrich expressiveness and it's also useful in accessibility and black-and-white printing scenarios. To achieve this, we offer three methods in increasing order of complexity and usage cost:
We have built three common patterns into the g-pattern, and the appearance can be easily adjusted through parameters. This is also the simplest way to use pattern:
The usage is as follows, first install the dependencies:
$ npm install @antv/g-pattern --save;
Then you can use the built-in patterns. In this example:
import { lines } from '@antv/g-pattern';chart//... Omit other imperative calls.style('fill', (_, idx) => {return {image: lines({backgroundColor: colors[idx],backgroundOpacity: 0.65,stroke: colors[idx],lineWidth: 4,spacing: 5,}),repetition: 'repeat',transform: 'rotate(30)',};});
The effect is as follows:
For more detailed parameter meanings and effects, see complete g-pattern API。
When the above-mentioned built-in patterns do not meet the requirements, you can use G API to customize, just like describing the scene.
In this example, we first get document object from context, create a rect and a path by document.createElement, and using them as pattern sources:
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',};});
The effect is as follows:
For more usage, please refer to G API。
Refer to G API, other available patterns sources include:
'http://example.png'
Among them, image URL, HTMLImageElement, and HTMLVideoElement are all static resources, while HTMLCanvasElement can be used to programmatically generate patterns, with the following results:
In this example, we used HTMLCanvasElement
with canvas API to customize:
// 程序化生成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' };});
It is not difficult to see that this programmatic generation method requires the users to have deep understanding of canvas API, but it also offers the highest level of flexibility.