rough

相比方方正正的常规图形,手绘风格能带给人可爱轻松之感。

有不少基于 rough.js 的图表库就是这么做的,例如 roughViz.jsrough-charts 等。

借助开箱即用的渲染插件,在 G2 中我们也能轻松完成手绘风格的切换。

开始使用

首先安装 @antv/g-plugin-rough-canvas-renderer

npm install @antv/g-plugin-rough-canvas-renderer --save

然后在插件列表中引入:

import { Plugin } from '@antv/g-plugin-rough-canvas-renderer';

const chart = new Chart({
  container: 'container',
  plugins: [new Plugin()],
});

仅需要一行改动即可完成风格转换。在该示例中,我们通过 fillStyle 指定了 'zigzag' 这种类似连续涂鸦笔迹的填充风格:

chart.options({
  type: 'interval',
  data: [
    { month: 'Jan.', profit: 387264, start: 0, end: 387264 },
    //...
  ],
  encode: {
    x: 'month',
    y: ['end', 'start'],
    color: (d) =>
      d.month === 'Total' ? 'Total' : d.profit > 0 ? 'Increase' : 'Decrease',
  },
  style: {
    strokeWidth: 2,
    // 指定填充风格
    fillStyle: 'zigzag',
  },
});

chart.render();

效果如下,可以看到原本的填充色活泼了起来! rough

当然 fillStyle 还有很多填充方式,下图展示了目前支持的所有效果。更多选项详见 @antv/g-plugin-rough-canvas-renderer 文档

rough

最后,选择一款手绘风格的字体能让整体风格趋于统一。在上面的示例中我们选择了 'Gaegu',可以参考如何加载外部字体

FAQ

在 SVG 渲染器如何使用?

G2 使用 g-canvas 作为默认渲染器。如果切换到 g-svg,也有对应的手绘风格插件可以选择:@antv/plugin-rough-svg-renderer,使用方式完全一致。

无障碍模式下的应用

使用 fillStyle 代替 fill 能实现类似 Pattern 的效果,因此在无障碍模式下也有不错的应用场景,例如考虑色弱人士和黑白打印。

在下面的示例中,我们将 fill/stroke 都设置和黑色,将 fillStyle 作为颜色属性:

chart.options({
  type: 'interval',
  // ... 省略 data、transform 等配置
  scale: {
    color: {
      range: [
        'hachure',
        'solid',
        'zigzag',
        'cross-hatch',
        'dots',
        'dashed',
        'zigzag-line',
      ],
    },
  },
  style: {
    fill: 'black',
    stroke: 'black',
    strokeWidth: '4',
    colorAttribute: 'fillStyle',
  },
});

效果如下:

rough
全站搜索
文档与示例输入关键词开始搜索

输入关键词,查找文档、API 与示例

选择打开Esc关闭