1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| function generateQRCode(url, config = {}, icon, fit = "contain") { let imgExt = ["png", "jpg", "jpeg", "bmp", "gif"]; if (imgExt.includes(Utils.getFileExtName(icon))) { let t = Date.now(); icon = icon + `?v=${t}`; } let _config = { errorCorrectionLevel: "H", width: 300, height: 200, color: { dark: "#000000", light: "#FFFFFF", }, ...config, }; if (_config.widh !== _config.height) { let max = Math.max(_config.width, _config.height); _config.width = _config.height = max; } let canvas = await QRCode.toCanvas(url, _config); let ctx = canvas.getContext("2d"); let scale = 0.3; let img = new Image(); img.setAttribute("crossOrigin", "Anonymous"); img.src = icon; return new Promise((resolve) => { try { img.onload = () => { ctx.fillStyle = "white"; let rectW = _config.width * scale; ctx.rect( (_config.width - rectW) / 2, (_config.height - rectW) / 2, _config.width * scale, _config.height * scale ); ctx.fill(); let max = Math.max(img.width, img.height); const scaleFit = rectW / max; let w = img.width * scaleFit; let h = img.height * scaleFit; ctx.drawImage( img, (_config.width - w) / 2, (_config.height - h) / 2, w, h ); resolve(canvas.toDataURL()); }; } catch (error) { resolve(canvas.toDataURL()); } }); }
|