flower-mp/miniprogram_npm/tdesign-miniprogram/qrcode/components/qrcode-canvas/qrcode-canvas.js
2025-09-16 10:26:42 +08:00

1 line
2.7 KiB
JavaScript

import{__awaiter,__decorate}from"tslib";import props from"./props";import useQRCode from"../../hooks/useQRCode";import{SuperComponent,wxComponent}from"../../../common/src/index";import{DEFAULT_MINVERSION,excavateModules}from"../../../common/shared/qrcode/utils";let QRCode=class extends SuperComponent{constructor(){super(...arguments),this.properties=props,this.lifeTimes={ready(){this.checkdefaultValue(),this.initCanvas()}},this.observers={"**":function(){this.checkdefaultValue(),this.initCanvas()}},this.methods={initCanvas(){return __awaiter(this,void 0,void 0,function*(){wx.createSelectorQuery().in(this).select("#qrcodeCanvas").fields({node:!0,size:!0}).exec(e=>__awaiter(this,void 0,void 0,function*(){var t;if(!(null===(t=e[0])||void 0===t?void 0:t.node))return;const o=e[0].node,i=o.getContext("2d");yield this.drawQrcode(o,i)}))})},drawQrcode(e,t){var o,i,r;return __awaiter(this,void 0,void 0,function*(){if(!t)return;const{value:a,icon:l,size:n,iconSize:s,level:d,bgColor:c,color:h,includeMargin:u,marginSize:v}=this.properties,g=this.getSizeProp(s);try{const s=useQRCode({value:a,level:d,minVersion:DEFAULT_MINVERSION,includeMargin:u,marginSize:v,size:n,imageSettings:l?{src:l,width:g.width,height:g.height,excavate:!0}:void 0}),m=wx.getWindowInfo().pixelRatio||1;e.width=n*m,e.height=n*m;const p=n*m/s.numCells;t.scale(p,p),t.fillStyle=c,t.fillRect(0,0,s.numCells,s.numCells);let C=s.cells;l&&(null===(o=s.calculatedImageSettings)||void 0===o?void 0:o.excavation)&&(C=excavateModules(s.cells,s.calculatedImageSettings.excavation)),t.fillStyle=h,C.forEach((e,o)=>{e.forEach((e,i)=>{e&&t.fillRect(i+s.margin,o+s.margin,1.05,1.05)})}),l&&(yield this.drawCenterIcon(e,t,(null===(i=s.calculatedImageSettings)||void 0===i?void 0:i.w)||0,(null===(r=s.calculatedImageSettings)||void 0===r?void 0:r.h)||0,s.numCells)),this.triggerEvent("drawCompleted")}catch(e){this.triggerEvent("drawError",{error:e})}})},drawCenterIcon(e,t,o,i,r){return __awaiter(this,void 0,void 0,function*(){const a=e.createImage();yield new Promise((e,t)=>{a.onload=e,a.onerror=t,a.src=this.properties.icon});const l=Math.floor((r-o)/2),n=Math.floor((r-i)/2);t.globalAlpha=1,t.drawImage(a,l,n,o,i)})},getSizeProp:e=>e?"number"==typeof e?{width:e,height:e}:{width:e.width,height:e.height}:{width:0,height:0},checkdefaultValue(){const e={bgColor:"",color:""};let t=!1;const{bgColor:o,color:i}=this.properties,{bgColor:r,color:a}=props;""===o&&r.value&&(e.bgColor=r.value,t=!0),""===i&&a.value&&(e.color=a.value,t=!0),t&&this.setData(e)},getCanvasNode(){return new Promise(e=>{wx.createSelectorQuery().in(this).select("#qrcodeCanvas").fields({node:!0,size:!0}).exec(t=>{var o;e(null===(o=t[0])||void 0===o?void 0:o.node)})})}}}};QRCode=__decorate([wxComponent()],QRCode);export default QRCode;