TL;DR G2Plot 是一个基于 G2 图形语法(the Grammar of Graphics)的通用统计图表库。基于 G2 栈,能够实现各种意想不到到的成果和能力。
二维码是什么,草料二维码是什么,我就不细说了,应该进来这篇文章的同学都晓得的。这里我就直入正题,介绍怎么实现超强自定义能力的二维码能力怎么来实现?
先来个最简略的成果预览:
最终产出了一个 G2Plot 的扩大包 G2Plot-QRCode,欢送试用和 star。
原理
G2Plot 是一个可视化通用图表库,所以这里的原理是以一个图表的思路去看二维码是什么?几个点:
- 二维码实质其实是一个简化的色块图
色块图能够看出数据在 x y 地位上的热力状况。
二维码在色块图的根底上,须要解决:
- x轴,y轴全副暗藏
- 色块大小间接填充单元格
- 色块的色彩依据地位 i j 来填充
- 二维码数据是一个数组,其中蕴含有 i j 索引地位
通过 i j 索引来惟一确定一个单元格,而后单元格具体是什么色彩,须要看二维码的原理构造。
这里咱们须要解决的是三个:
- 前景还是背景,个别状况下前景是彩色、背景是红色。
- 是否是 detection position 元素?
- 是三个 detection position 哪一个?
- 核心图标对于 G2Plot 来说其实是一个核心的辅助元素(annotation)
这个就更容易了, G2 的 annotation 能够间接绘制一个 image 类型的 annotation。
实现
- 理解一下 G2Plot 扩大包的开发方式
- 生成二维码的 pixel 数据
二维码的协定解析和生成模块十分多,咱们就不反复造轮子了,间接应用社区的货色。
import qrcode from 'qrcode-generator';const qr = qrcode(typeNumber, correctLevel);qr.addData(data);qr.make();
这个就能够获取一个二维数组,数组的每一个元素,只有一个信息,isDark。其实就是标记前景还是背景单元格。
- 二维码的 pixel 数据辨认 detection
基于上述的数据,以及二维码的编码协定,咱们能够去实现别出 detection,以及 detection 的左上、右上、左下方位。
原理是 detection 的大小是固定的 7 * 7 的矩阵,而后地位在左上、右上、左下,联合二维码的 pixel count 即可进行解析,这里不贴源码了,具体能够看这里。
最初产出的数据结构为:
export type PixelData = { i: number; j: number; isBackground: boolean; isForeground: boolean; detection: 'inner' | 'middle' | 'outer'; detectionPosition: 'tl' | 'tr' | 'bl';};
- 基于 G2Plot 扩大机制生成色块图
整顿应用 G2 图形语法绘制图表。
chart .polygon() .position('i*j') .color('isForeground', (v: boolean) => { return v ? foregroundColor : backgroundColor; }) .style( 'i*j*isForeground*isBackground*detection*detectionPosition', (i, j, isForeground, isBackground, detection, detectionPosition) => { return typeof pixelStyle === 'function' ? pixelStyle({ i, j, isForeground, isBackground, detection, detectionPosition }) : {}; },);
这里解决了几个事件:
- 绘制矩形色块图
- 映射前景背景色彩
- 实现依据 i j 像素级别的款式设置
- icon 实现
icon 其实就是在图表画布的最两头,绘制一个 image,并且能够指定宽高,image 地址。
chart.annotation().shape({ render: (container) => { container.addShape('image', { attrs: { // 核心地位 x: (width - imageWdith) / 2, y: (height - imageHeight) / 2, // 宽高 width: imageWdith, height: imageHeight, // 图片地址 img: image, }, }); },});
应用
如何应用放到最初。因为 G2Plot-QRCode 是 G2Plot 的一个扩大包,所以应用形式上和 G2Plot 内置图表的应用完全一致。
import { G2Plot } from '@antv/g2plot';import { adaptor, defaultOptions } from 'g2plot-qrcode';const qr = new G2Plot('container', { // 二维码文本 data: 'Hello, g2plot qrcode!', // 间距 padding: 8, // 宽高 width: 120, height: 120, // 背景前景色彩 backgroundColor: 'white', foregroundColor: 'black', typeNumber: 0, correctLevel: 'H', // L M H Q // 款式自定义 pixelStyle: (pixelData) => ({}),}, adaptor, defaultOptions);qr.render();
后续布局
二维码库那么多,基于 G2Plot 做二维码带来的益处在于:
- 每个单元格的色块款式,能够多种多样,随便自定义
- 二维码的出场、更新动画能够十分炫酷
- 二维码不再是动态的图片,而是能够进行动静交互的
以上也是后续的布局内容,欢送有趣味的同学来搞。全副代码在这里,它依赖的 G2Plot 也欢送 star 和应用。