u-qrcode.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <template>
  2. <view class="u-qrcode"
  3. :id="rootId"
  4. :style="{
  5. width: useRootHeightAndWidth ? '100%' : 'auto',
  6. height: useRootHeightAndWidth ? '100%' : 'auto',
  7. }"
  8. @longpress="longpress">
  9. <view class="u-qrcode__content" @click="preview">
  10. <!-- #ifdef MP || H5 -->
  11. <canvas
  12. class="u-qrcode__canvas"
  13. :id="cid"
  14. :canvas-id="cid"
  15. type="2d"
  16. :style="{ width: sizeLocal + unit, height: sizeLocal + unit }" />
  17. <!-- #endif -->
  18. <!-- #ifdef APP-PLUS -->
  19. <canvas
  20. class="u-qrcode__canvas"
  21. :id="cid"
  22. :canvas-id="cid"
  23. :style="{ width: sizeLocal + unit, height: sizeLocal + unit }" />
  24. <!-- #endif -->
  25. <!-- #ifdef APP-NVUE -->
  26. <web-view v-if="icon != ''" ref="web" src="/static/app-plus/up-canvas/local.html"
  27. :style="'width:' + sizeLocal + 'px;height:' + sizeLocal + 'px'"
  28. @onPostMessage="_onMessage" />
  29. <gcanvas v-else class="u-qrcode__canvas" ref="gcanvess"
  30. :style="{ width: sizeLocal + unit, height: sizeLocal + unit }">
  31. </gcanvas>
  32. <!-- #endif -->
  33. <view v-if="showLoading && loading" class="u-qrcode__loading"
  34. :style="{ width: sizeLocal + unit, height: sizeLocal + unit }">
  35. <up-loading-icon vertical :text="loadingText" textSize="14px"></up-loading-icon>
  36. </view>
  37. </view>
  38. </view>
  39. </template>
  40. <script>
  41. import QRCode from "./qrcode.js"
  42. import { sleep } from '../../libs/function/index';
  43. // #ifdef APP-NVUE
  44. // https://github.com/dcloudio/NvueCanvasDemo/blob/master/README.md
  45. import {
  46. enable,
  47. WeexBridge,
  48. Image as GImage
  49. } from '../../libs/util/gcanvas/index.js';
  50. import { nextTick } from "vue";
  51. // #endif
  52. let qrcode
  53. // 20260201不能在data中存储canvas,否则会导致在微信小程序getContext获取不到canvas对象报错Cannot read property 'type'
  54. let canvas = null
  55. export default {
  56. name: "u-qrcode",
  57. props: {
  58. cid: {
  59. type: String,
  60. default: () => {
  61. return `u-qrcode-canvas${Math.floor(Math.random() * 1000000)}`
  62. }
  63. },
  64. size: {
  65. type: Number,
  66. default: 200
  67. },
  68. unit: {
  69. type: String,
  70. default: 'px'
  71. },
  72. show: {
  73. type: Boolean,
  74. default: true
  75. },
  76. val: {
  77. type: String,
  78. default: ''
  79. },
  80. background: {
  81. type: String,
  82. default: '#ffffff'
  83. },
  84. foreground: {
  85. type: String,
  86. default: '#000000'
  87. },
  88. pdground: {
  89. type: String,
  90. default: '#000000'
  91. },
  92. icon: {
  93. type: String,
  94. default: ''
  95. },
  96. iconSize: {
  97. type: Number,
  98. default: 40
  99. },
  100. lv: {
  101. type: Number,
  102. default: 3
  103. },
  104. onval: {
  105. type: Boolean,
  106. default: true
  107. },
  108. loadMake: {
  109. type: Boolean,
  110. default: true
  111. },
  112. usingComponents: {
  113. type: Boolean,
  114. default: true
  115. },
  116. showLoading: {
  117. type: Boolean,
  118. default: true
  119. },
  120. loadingText: {
  121. type: String,
  122. default: '生成中'
  123. },
  124. allowPreview: {
  125. type: Boolean,
  126. default: false
  127. },
  128. // 是否使用根节点宽高
  129. useRootHeightAndWidth: {
  130. type: Boolean,
  131. default: () => false
  132. },
  133. },
  134. emits: ['preview', 'result', 'longpressCallback'],
  135. data() {
  136. return {
  137. loading: false,
  138. result: '',
  139. popupShow: false,
  140. list: [
  141. {
  142. name: '保存二维码',
  143. }
  144. ],
  145. rootId: `rootId${Number(Math.random() * 100).toFixed(0)}`,
  146. ganvas: null,
  147. canvasObj: {},
  148. sizeLocal: this.size,
  149. ctx: null,
  150. _ready: false
  151. }
  152. },
  153. async mounted(){
  154. // 如果使用根节点的宽高 则 重新设置 size
  155. if(this.useRootHeightAndWidth){
  156. await this.setNewSize()
  157. }
  158. canvas = await this.getCanvasNode(this.cid)
  159. if (!canvas) return
  160. // #ifdef MP
  161. // 不清楚是小程序的bug还是什么原因,canvas的node节点宽高和设置的宽高不一致 重新设置下
  162. canvas.width = this.sizeLocal
  163. canvas.height = this.sizeLocal
  164. // #endif
  165. // #ifdef APP-PLUS-NVUE
  166. this.isNvue = true
  167. // #endif
  168. this.ctx = this.getUPCanvasContext('2d')
  169. if (this.loadMake) {
  170. if (!this._empty(this.val)) {
  171. setTimeout(() => {
  172. setTimeout(()=>{
  173. this._makeCode()
  174. })
  175. }, 0);
  176. }
  177. }
  178. },
  179. methods: {
  180. _onMessage(e) {
  181. // console.log('post message', e)
  182. const message = e.detail.data[0]
  183. switch (message.action) {
  184. // web-view 初始化完毕
  185. case 'onJSBridgeReady':
  186. this._ready = true
  187. this.$refs.web.evalJs('setContent('+JSON.stringify(this.$props) +')')
  188. break
  189. // qrcodeOk
  190. case 'qrcodeOk':
  191. this._result(message.imageData)
  192. // this.$emit('load')
  193. break
  194. }
  195. },
  196. _makeCode() {
  197. let that = this
  198. if (!canvas) return
  199. if (!this._empty(this.val)) {
  200. // #ifndef APP-NVUE
  201. this.loading = true
  202. // #endif
  203. // nvue下时因为gcanvas的GImage不生效,因此icon模式会采用webview
  204. if ((this.icon == '' && that.isNvue) || !that.isNvue) {
  205. qrcode = new QRCode({
  206. vuectx: that, // 上下文环境
  207. canvasId: that.cid, // canvas-id
  208. ctx: that.ctx,
  209. isNvue: that.isNvue,
  210. usingComponents: that.usingComponents, // 是否是自定义组件
  211. showLoading: false, // 是否显示loading
  212. loadingText: that.loadingText, // loading文字
  213. text: that.val, // 生成内容
  214. size: that.sizeLocal, // 二维码大小
  215. background: that.background, // 背景色
  216. foreground: that.foreground, // 前景色
  217. pdground: that.pdground, // 定位角点颜色
  218. correctLevel: that.lv, // 容错级别
  219. image: that.icon, // 二维码图标
  220. imageSize: that.iconSize,// 二维码图标大小
  221. cbResult: function (res) { // 生成二维码的回调
  222. that._result(res)
  223. },
  224. });
  225. }
  226. } else {
  227. uni.showToast({
  228. title: '二维码内容不能为空',
  229. icon: 'none',
  230. duration: 2000
  231. });
  232. }
  233. },
  234. _clearCode() {
  235. this._result('')
  236. qrcode.clear()
  237. },
  238. _saveCode() {
  239. let that = this;
  240. if (this.result != "") {
  241. uni.saveImageToPhotosAlbum({
  242. filePath: that.result,
  243. success: function () {
  244. uni.showToast({
  245. title: '二维码保存成功',
  246. icon: 'success',
  247. duration: 2000
  248. });
  249. }
  250. });
  251. } else {
  252. this.toTempFilePath({
  253. success: res => {
  254. that.result = res.tempFilePath
  255. uni.saveImageToPhotosAlbum({
  256. filePath: that.result,
  257. success: function () {
  258. uni.showToast({
  259. title: '二维码保存成功',
  260. icon: 'success',
  261. duration: 2000
  262. });
  263. }
  264. });
  265. },
  266. fail: err => {
  267. }
  268. })
  269. }
  270. },
  271. preview(e) {
  272. // 预览图片
  273. // console.log(this.result)
  274. if (this.allowPreview) {
  275. uni.previewImage({
  276. urls: [this.result],
  277. longPressActions: {
  278. itemList: ['保存二维码图片'],
  279. success: function(data) {
  280. // console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
  281. switch (data.tapIndex) {
  282. case 0:
  283. that._saveCode();
  284. break;
  285. }
  286. },
  287. fail: function(err) {
  288. console.log(err.errMsg);
  289. }
  290. }
  291. });
  292. }
  293. this.$emit('preview', {
  294. url: this.result
  295. }, e)
  296. },
  297. async toTempFilePath({success, fail}) {
  298. if (this.ct) {
  299. this.ctx.toTempFilePath(
  300. 0,
  301. 0,
  302. this.sizeLocal,
  303. this.sizeLocal,
  304. this.sizeLocal,
  305. this.sizeLocal,
  306. "",
  307. 1,
  308. res => {
  309. success(res)
  310. }
  311. );
  312. }
  313. else {
  314. // #ifdef H5
  315. success({
  316. tempFilePath: this.ctx.canvas.toDataURL("image/png", 1)
  317. })
  318. // #endif
  319. // #ifndef H5
  320. uni.canvasToTempFilePath(
  321. {
  322. canvasId: this.cid,
  323. success :res => {
  324. success(res)
  325. },
  326. fail: fail
  327. },
  328. this)
  329. // #endif
  330. }
  331. },
  332. async longpress() {
  333. this.toTempFilePath({
  334. success: res => {
  335. this.$emit('longpressCallback', res.tempFilePath)
  336. },
  337. fail: err => {
  338. }
  339. })
  340. },
  341. /**
  342. * 使用根节点宽高 设置新的size
  343. * @return {Promise<void>}
  344. */
  345. async setNewSize(){
  346. const rootNode = await this.getCanvasNode(this.rootId, false);
  347. const { width , height } = rootNode;
  348. // 将最短的设置为二维码 的size
  349. if(width > height){
  350. this.sizeLocal = height
  351. }
  352. else{
  353. this.sizeLocal = width
  354. }
  355. },
  356. /**
  357. * 获取节点
  358. * @param id 节点id
  359. * @param isCanvas 是否为Canvas节点
  360. * @return {Promise<unknown>}
  361. */
  362. async getCanvasNode(id, isCanvas = true) {
  363. let that = this
  364. return new Promise((resolve, reject) => {
  365. try {
  366. // #ifdef APP-NVUE
  367. setTimeout(() => {
  368. /*获取元素引用*/
  369. this.ganvas = this.$refs["gcanvess"]
  370. /*通过元素引用获取canvas对象*/
  371. let canvasNode = enable(this.ganvas, {
  372. bridge: WeexBridge
  373. })
  374. resolve(canvasNode)
  375. }, 200)
  376. // #endif
  377. // #ifndef APP-PLUS-NVUE
  378. const query = uni.createSelectorQuery().in(that).select(`#${id}`);
  379. query.fields({
  380. node: true,
  381. size: true
  382. })
  383. .exec((res) => {
  384. if (isCanvas) {
  385. if (res[0]?.node) {
  386. resolve(res[0].node)
  387. } else {
  388. resolve(false)
  389. console.error("获取节点出错", res)
  390. }
  391. } else {
  392. resolve(res[0])
  393. }
  394. })
  395. // #endif
  396. } catch (e) {
  397. console.error("获取节点失败", e)
  398. }
  399. })
  400. },
  401. getUPCanvasContext() {
  402. // #ifdef APP-PLUS
  403. return uni.createCanvasContext(this.cid, this);
  404. // #endif
  405. // #ifdef APP-PLUS-NVUE || MP || H5
  406. return canvas.getContext('2d');
  407. // #endif
  408. },
  409. drawImage(url, x, y, w, h) {
  410. try {
  411. let img = {}
  412. // #ifdef APP-NVUE
  413. img = new GImage();
  414. // #endif
  415. // #ifdef H5
  416. // APP下不支持会一直卡住
  417. img = new Image();
  418. // #endif
  419. // #ifdef MP
  420. // 小程序2d
  421. // https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Canvas.createImage.html
  422. img = canvas.createImage();
  423. // #endif
  424. // #ifdef APP-NVUE
  425. let that = this
  426. // console.log(img)
  427. img.onload = function(){
  428. if (process.env.NODE_ENV === 'development') {
  429. console.log('drawImage绘制2...')
  430. }
  431. that.cxt.drawImage(img, x, y, w, h);
  432. }
  433. // #endif
  434. // #ifdef H5 || MP
  435. img.onload = () => {
  436. this.ctx.drawImage(img, x, y, w, h);
  437. };
  438. // #endif
  439. img.src = url;
  440. // #ifdef APP-VUE
  441. this.ctx.drawImage(url, x, y, w, h);
  442. // #endif
  443. } catch (error) {
  444. console.log('drawImage绘制出错', error)
  445. }
  446. },
  447. selectClick(index) {
  448. switch (index) {
  449. case 0:
  450. alert('保存二维码')
  451. this._saveCode();
  452. break;
  453. }
  454. },
  455. _result(res) {
  456. this.loading = false;
  457. this.result = res;
  458. this.$emit('result', res);
  459. },
  460. _empty(v) {
  461. let tp = typeof v,
  462. rt = false;
  463. if (tp == "number" && String(v) == "") {
  464. rt = true
  465. } else if (tp == "undefined") {
  466. rt = true
  467. } else if (tp == "object") {
  468. if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true
  469. } else if (tp == "string") {
  470. if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
  471. } else if (tp == "function") {
  472. rt = false
  473. }
  474. return rt
  475. },
  476. },
  477. watch: {
  478. size: function (n, o) {
  479. if (n != o && !this._empty(n)) {
  480. this.cSize = n
  481. if (!this._empty(this.val)) {
  482. setTimeout(() => {
  483. this._makeCode()
  484. }, 100);
  485. }
  486. }
  487. },
  488. val: function (n, o) {
  489. if (this.onval) {
  490. if (n != o && !this._empty(n)) {
  491. setTimeout(() => {
  492. this._makeCode()
  493. }, 0);
  494. }
  495. }
  496. }
  497. },
  498. computed: {
  499. }
  500. }
  501. </script>
  502. <style lang="scss" scoped>
  503. .u-qrcode {
  504. &__loading {
  505. display: flex;
  506. justify-content: center;
  507. align-items: center;
  508. background-color: #f7f7f7;
  509. position: absolute;
  510. top: 0;
  511. bottom: 0;
  512. left: 0;
  513. right: 0;
  514. }
  515. /* #ifdef MP-TOUTIAO */
  516. /**字节小程序在编译时会出现一个 [hidde]:{ display: none !important; } 这个样式
  517. * 会导致canvas 隐藏掉 没有找到具体原因先这样处理
  518. */
  519. &__canvas {
  520. display: block !important;
  521. }
  522. /* #endif */
  523. &__content {
  524. position: relative;
  525. &__canvas {
  526. position: fixed;
  527. top: -99999rpx;
  528. left: -99999rpx;
  529. z-index: -99999;
  530. }
  531. }
  532. }
  533. </style>