碧桂园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 lines
9.9 KiB

  1. import {CrsClient} from "./crsClient";
  2. import {CryptoJS} from "./CryptoJS";
  3. const systemInfo = wx.getSystemInfoSync();
  4. const SELECT_TYPE = {
  5. NONE: 0,
  6. IMAGE: 1,
  7. VIDEO: 2,
  8. };
  9. Page({
  10. data: {
  11. showOverlay: true,
  12. showSelect: false,
  13. SELECT_TYPE: SELECT_TYPE,
  14. selectType: 0,
  15. //CRS配置
  16. config: {
  17. apiKey: 'a9abd99b2dfb3a5bee964cbb0bced0ae', // EasyAR开发中心 - API KEY - API Key
  18. apiSecret: '483e000a38265687c058efb7ab66cbc0917a3331b6dbf5482df46c76cb749529', // EasyAR开发中心 - API KEY - API Secret
  19. crsAppId: '8911f4b8f03725e300ca4130c01f27e9', // EasyAR开发中心 - 云服务 - 云识别管理 - 云识别库信息 - CRS AppId
  20. token: '',
  21. clientHost: 'https://bd9b3490fe845642e600cf53f0cd64b8.cn1.crs.easyar.com:8443', //服务器一般不变
  22. jpegQuality: 0.7, //JPEG压缩质量,建议不低于70%
  23. minInterval: 2000, //最短的两次CRS请求间隔
  24. },
  25. //识别到这个数组中的ID就触发内容
  26. targetIds: [
  27. "6c27e0a1-e4ca-424d-9062-4c8ec676a5ad",
  28. "ec72a9a2-20d5-4b86-82db-05f29e1c0fbb",
  29. "f0bdba05-e610-4d1c-811a-5034ccc0d1f7",
  30. "79014ee9-60c7-4a0c-81ed-0d5889a7ecc9"
  31. ],
  32. showLoading: false,
  33. showLoadingText: "",
  34. },
  35. /** @type {CameraFrameListener} 相机帧回调 */
  36. listener: undefined,
  37. /** @type {HTMLCanvasElement} canvas对象 */
  38. canvas: undefined,
  39. /** @type {boolean} 是否需要持续识别,在点击“识别体验”之后和识别成功之前为true */
  40. runningCrs: undefined,
  41. /** @type {boolean} 当前是否正在进行CRS请求 */
  42. busy: undefined,
  43. /** @type {CrsClient} 负责发起CRS请求的对象 */
  44. crsClient: undefined,
  45. /** @type {number} 最后一次CRS请求的事件,用于判断是否满足最短请求间隔 */
  46. last: undefined,
  47. onLoad: function () {
  48. this.daojishi() // 默认进入页面10S后退出
  49. },
  50. onReady: function () {
  51. if (systemInfo.platform === "devtools") { //开发工具不会触发initdone事件,于是在onReady手动触发
  52. this.onCameraInit();
  53. }
  54. // 获取token
  55. this.queryToken().then(msg => {
  56. console.log('token1')
  57. console.log(msg)
  58. this.data.config.token = msg;
  59. }).catch(err => {
  60. console.info(err);
  61. });
  62. },
  63. daojishi(){
  64. var t = 10;
  65. var timer = setInterval(function(){
  66. t--;
  67. if(t==3){
  68. wx.showToast({
  69. icon: 'none',
  70. title: '扫描次数过多',
  71. })
  72. }
  73. if(t<0){
  74. clearInterval(timer);
  75. wx.navigateBack({
  76. delta: 1,
  77. })
  78. }
  79. console.log(t)
  80. }, 1000)
  81. },
  82. showLoading(text) {
  83. this.setData({
  84. showLoading: true,
  85. showLoadingText: text,
  86. });
  87. },
  88. hideLoading() {
  89. this.setData({
  90. showLoading: false,
  91. });
  92. },
  93. //图像识别部分:
  94. onShow: function () {
  95. if (this.listener) this.listener.start(); //页面隐藏时相机帧的监听会自动停止,但恢复展示时不会自动启动,这里手动启动
  96. this.scan()
  97. },
  98. scan: function () {
  99. this.runningCrs = true;
  100. this.setData({
  101. showOverlay: false,
  102. showContent: false,
  103. selectType: SELECT_TYPE.NONE,
  104. });
  105. this.showLoading("识别中");
  106. },
  107. onCameraInit: function () {
  108. //找到canvas对象
  109. const query = wx.createSelectorQuery();
  110. query.select('#capture')
  111. .fields({node: true})
  112. .exec((res) => {
  113. const canvas = res[0].node;
  114. //设置canvas内部尺寸为480*640,frame-size="medium"的设置下相机帧大多是480*640
  115. canvas.width = 480;
  116. canvas.height = 640;
  117. this.canvas = canvas;
  118. this.crsClient = new CrsClient(this.data.config, this.canvas);
  119. //开始监听相机帧
  120. let cameraContext = wx.createCameraContext();
  121. this.listener = cameraContext.onCameraFrame(frame => {
  122. if (!this.canvas) return;
  123. let canvas = this.canvas;
  124. //如果尺寸不匹配,就修改canvas尺寸以适应相机帧
  125. if (canvas.width !== frame.width || canvas.height !== frame.height) {
  126. canvas.width = frame.width;
  127. canvas.height = frame.height;
  128. }
  129. this.queryImage(frame);
  130. });
  131. this.listener.start();
  132. });
  133. },
  134. queryImage: function (frame) {
  135. if (!this.runningCrs || this.busy || !this.crsClient) return;
  136. //最短的两次CRS请求间隔
  137. let now = new Date().getTime();
  138. if (this.last && (now - this.last < this.data.config.minInterval)) return;
  139. this.last = now;
  140. this.busy = true; //如果正在进行CRS请求,就不允许再次请求
  141. this.crsClient.queryImage(frame).then(res => {
  142. if (!this.runningCrs) return; //避免在停止后仍然触发
  143. let result = res.result;
  144. if (!result) return;
  145. if (result.target) {
  146. console.log("识别成功");
  147. this.runningCrs = false;
  148. this.hideLoading();
  149. let base64 = result.target.meta
  150. let web = this.base64_decode(base64)
  151. // 解析跳转链接
  152. wx.navigateTo({
  153. url: '../out/index?web=' + web + '&index=2',
  154. })
  155. // todo: 解析meta中的信息,触发业务逻辑
  156. //如果待触发的id列表中存在识别到的这个id,就触发
  157. if (this.data.targetIds.find(targetId => targetId === result.target.meta)) {
  158. this.onResult(result.target.meta);
  159. }
  160. } else {
  161. console.log("识别失败");
  162. }
  163. this.busy = false;
  164. }).catch(e => {
  165. this.busy = false;
  166. }); //小程序iOS端不支持finally,所以在then和catch里分别设置busy = false
  167. },
  168. onResult: function (target) {
  169. console.log("触发内容!");
  170. console.log(target);
  171. if (target) {
  172. console.log("meta base64:", target);
  173. }
  174. this.setData({
  175. showOverlay: false,
  176. showContent: true,
  177. selectType: SELECT_TYPE.IMAGE,
  178. });
  179. },
  180. //界面:
  181. back: function () {
  182. this.runningCrs = false;
  183. this.setData({
  184. showOverlay: true,
  185. showContent: false,
  186. selectType: SELECT_TYPE.NONE,
  187. });
  188. this.hideLoading();
  189. },
  190. experience: function () {
  191. this.setData({
  192. showOverlay: false,
  193. showContent: true,
  194. selectType: SELECT_TYPE.IMAGE,
  195. });
  196. },
  197. download: function () {
  198. wx.saveImageToPhotosAlbum({
  199. filePath: "/images/namecard.jpg",
  200. success: res => {
  201. wx.showToast({title: "已保存到相册", icon: "none"});
  202. },
  203. fail: res => {
  204. wx.showToast({title: "保存失败", icon: "none"});
  205. },
  206. });
  207. },
  208. selectContent: function (e) {
  209. this.setData({
  210. selectType: e.currentTarget.dataset.contenttype,
  211. });
  212. },
  213. queryToken: function() { // 获取token
  214. return new Promise((resolve, reject) => {
  215. wx.request({
  216. url: 'https://cktest.2weisou.com/meta/ar/ar/getToken',
  217. method: 'get',
  218. data: {},
  219. header: {
  220. 'content-type': 'application/json'
  221. },
  222. success: res => resolve(res.data),
  223. fail: err => reject(err)
  224. });
  225. });
  226. },
  227. base64_decode(input) { // 解码,配合decodeURIComponent使用
  228. var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  229. var output = "";
  230. var chr1, chr2, chr3;
  231. var enc1, enc2, enc3, enc4;
  232. var i = 0;
  233. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  234. while (i < input.length) {
  235. enc1 = base64EncodeChars.indexOf(input.charAt(i++));
  236. enc2 = base64EncodeChars.indexOf(input.charAt(i++));
  237. enc3 = base64EncodeChars.indexOf(input.charAt(i++));
  238. enc4 = base64EncodeChars.indexOf(input.charAt(i++));
  239. chr1 = (enc1 << 2) | (enc2 >> 4);
  240. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  241. chr3 = ((enc3 & 3) << 6) | enc4;
  242. output = output + String.fromCharCode(chr1);
  243. if (enc3 != 64) {
  244. output = output + String.fromCharCode(chr2);
  245. }
  246. if (enc4 != 64) {
  247. output = output + String.fromCharCode(chr3);
  248. }
  249. }
  250. return this.utf8_decode(output);
  251. },
  252. utf8_decode(utftext) { // utf-8解码
  253. var string = '';
  254. let i = 0;
  255. let c = 0;
  256. let c1 = 0;
  257. let c2 = 0;
  258. while (i < utftext.length) {
  259. c = utftext.charCodeAt(i);
  260. if (c < 128) {
  261. string += String.fromCharCode(c);
  262. i++;
  263. } else if ((c > 191) && (c < 224)) {
  264. c1 = utftext.charCodeAt(i + 1);
  265. string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
  266. i += 2;
  267. } else {
  268. c1 = utftext.charCodeAt(i + 1);
  269. c2 = utftext.charCodeAt(i + 2);
  270. string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
  271. i += 3;
  272. }
  273. }
  274. return string;
  275. }
  276. });