UNPKG

taro-code

Version:

Taro.js barcode & qrcode, Image & Canvas

47 lines 2.07 kB
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { Canvas } from '@tarojs/components'; import { drawCanvasQRCode } from '../../common/canvas/qrcode'; import { waitForElement } from '../../common/canvas/element'; function usePrevious(state) { const ref = useRef(); useEffect(() => { ref.current = state; }); return ref.current; } const QRCodeCanvas = forwardRef((props, ref) => { const { className, text = '', size = 100, typeNumber = 2, errorCorrectLevel = 'M', style = {}, foregroundColor = '#000000', backgroundColor = '#FFF0FF', padding = 0, rootSelector, } = props; const id = 'taro-code-canvas-qrcode'; const widthString = size != null ? `${size}px` : ''; const heightString = size != null ? `${size}px` : ''; const finalStyle = Object.assign({ width: widthString, height: heightString }, style); const previousSize = usePrevious(size); const [canvasOutput, setCanvasOutput] = useState(); const drawOnce = async () => { const canvas = await waitForElement(id, rootSelector); setCanvasOutput(canvas); if (canvas != null) { const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, previousSize !== null && previousSize !== void 0 ? previousSize : size, previousSize !== null && previousSize !== void 0 ? previousSize : size); drawCanvasQRCode(text, { errorCorrectLevel, typeNumber, size, foregroundColor, backgroundColor, padding, canvas, }); } }; useEffect(() => { void drawOnce(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [props]); useImperativeHandle(ref, () => { return { canvas: canvasOutput }; }, [canvasOutput]); return React.createElement(Canvas, { id: id, canvasId: id, type: '2d', className: className, style: finalStyle }); }); export default QRCodeCanvas; //# sourceMappingURL=index.js.map