Taro生成二维码、条形码(小程序、H5)
插件使用 taro-code
github https://github.com/miaonster/taro-code
安装
taro 3.0 以上版本安装 taro3-code,下面的命令改成 yarn add taro3-code
yarn add taro-code
# or
npm install taro-code
使用
import { Barcode, QRCode } from 'taro-code'
class Code extends Taro.Component {
render() {
return (
<View>
<Barcode text='crayon' width={300} height={60} scale={4} />
<QRCode
text='crayon'
size={300}
scale={4}
errorCorrectLevel='M'
typeNumber={2}
/>
</View>
)
}
}
使用方式比较简单,就不多赘述了,现在讲一下其中遇到的问题
该二维码或条形码的生成,其中 width 和 height 是以 px 为单位
而小程序或H5中其宽高应动态适应
使用以下方法,根据你的设计尺寸图来动态计算出对应的 px 值即可(我这里设计图是750)
import Taro from '@tarojs/taro';
// 按缩放比例计算对应的px值(主要用于那些只能写死px的canvas等等,用此方法动态计算出px值)
const getPx = ( number, designWidth = 750 ) => {
const sys = Taro.getSystemInfoSync();
const scale = sys.screenWidth / designWidth; // 缩放比例
return Number(number * scale).toFixed(0); // 返回缩放后的值
}
export default {
px: getPx
}
import { Barcode, QRCode } from 'taro-code'
import _style from '@/utils/style';
class Code extends Taro.Component {
render() {
return (
<Barcode text='crayon' width={_style.px(540)} height={_style.px(160)} />
<QRCode text='crayon' size={_style.px(316)} />
)
}
}
注:return Number(number * scale).toFixed(0) 我这里限制了小数位, 因为计算出来的值存在无限小数的情况,width 或 height 存在无限小数的话会导致二维码或条形码生成失败
该插件博主仅在小程序端和H5端使用过,其他端情况暂时不明