TL;DR G2Plot 是一个基于 G2 图形语法(the Grammar of Graphics)的通用统计图表库。基于 G2 栈,能够实现各类意想不到到的效果和能力。
二维码是什么,草料二维码是什么,我就不细说了,应该进来这篇文章的同窗都知道的。这里我就直入正题,介绍怎么实现超强自定义能力的二维码能力怎么来实现?git
先来个最简单的效果预览:
最终产出了一个 G2Plot 的扩展包 G2Plot-QRCode,欢迎试用和 star。github
G2Plot 是一个可视化通用图表库,因此这里的原理是以一个图表的思路去看二维码是什么?几个点:typescript
色块图能够看出数据在 x y 位置上的热力状况。数组
二维码在色块图的基础上,须要处理:数据结构
经过 i j 索引来惟一肯定一个单元格,而后单元格具体是什么颜色,须要看二维码的原理结构。
这里咱们须要处理的是三个:动画
这个就更容易了, G2 的 annotation 能够直接绘制一个 image 类型的 annotation。编码
二维码的协议解析和生成模块很是多,咱们就不重复造轮子了,直接使用社区的东西。spa
import qrcode from 'qrcode-generator'; const qr = qrcode(typeNumber, correctLevel); qr.addData(data); qr.make();
这个就能够获取一个二维数组,数组的每个元素,只有一个信息,isDark。其实就是标记前景仍是背景单元格。code
基于上述的数据,以及二维码的编码协议,咱们能够去实现别出 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'; };
整理使用 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 }) : {}; }, );
这里处理了几个事情:
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 作二维码带来的好处在于: