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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
| /**
| * CQRCode
| * @author Tevin
| */
|
| <template>
| <view class="c-qr-code">
| <canvas ref="canvas"></canvas>
| <AtButton
| v-if="downloadable"
| type="primary"
| full
| :onClick="evt => handleSaveToAlbum()"
| >保存到手机</AtButton>
| </view>
| </template>
|
| <script>
| import Taro from '@tarojs/taro';
| import { $ } from '@tarojs/extend';
| import { AtButton } from 'taro-ui-vue';
| import QRCode from 'qrcode';
| import './cQrCode.scss';
|
| export default {
| name: 'CQRCode',
| components: {
| AtButton,
| },
| props: {
| content: {
| type: String,
| default: 'http://www.aisim.cn',
| },
| size: {
| type: Number,
| default: 200,
| },
| margin: {
| type: Number,
| default: 2,
| },
| // 是否显示保存到手机
| downloadable: {
| type: Boolean,
| default: false,
| },
| },
| data() {
| return {
| lastContent: '',
| };
| },
| methods: {
| handleSaveToAlbum() {
| if (process.env.TARO_ENV === 'h5') {
| const canvasBox = $(this.$refs.canvas.$el);
| const canvasDom = canvasBox.find('canvas')[0];
| const dataURL = canvasDom.toDataURL('image/png', 1);
| const a = document.createElement('a');
| a.download = 'qrcode.png';
| a.href = dataURL;
| a.dispatchEvent(new MouseEvent('click'));
| } else {
| // TODO: 小程序中下载
| }
| },
| _renderQRCodeH5(canvasDom) {
| QRCode.toCanvas(
| canvasDom,
| this.content,
| {
| width: this.size * 2,
| margin: this.margin,
| },
| err => {
| if (err) {
| console.error(err);
| return;
| }
| }
| );
| },
| },
| mounted() {
| if (process.env.TARO_ENV === 'h5') {
| const canvasBox = $(this.$refs.canvas.$el);
| const finderTimer = setInterval(() => {
| const canvasDom = canvasBox.find('canvas');
| if (canvasDom.length === 0) {
| return;
| }
| if (this.lastContent === this.content) {
| return;
| }
| this._renderQRCodeH5(canvasDom[0]);
| this.lastContent = this.content;
| }, 10);
| } else {
| // TODO: 小程序中获取canvas
| }
| },
| };
| </script>
|
|