碧桂园
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

287 linhas
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. onHide(){
  64. console.log('tuichu')
  65. clearInterval(timer);
  66. },
  67. daojishi(){
  68. var t = 10;
  69. var timer = setInterval(function(){
  70. t--;
  71. if(t<2){
  72. wx.showToast({
  73. icon: 'none',
  74. title: '扫描时间过长,请退出后重新扫描!',
  75. })
  76. }
  77. if(t<0){
  78. clearInterval(timer);
  79. wx.navigateBack({
  80. delta: 1,
  81. })
  82. }
  83. }, 1000)
  84. },
  85. showLoading(text) {
  86. this.setData({
  87. showLoading: true,
  88. showLoadingText: text,
  89. });
  90. },
  91. hideLoading() {
  92. this.setData({
  93. showLoading: false,
  94. });
  95. },
  96. //图像识别部分:
  97. onShow: function () {
  98. if (this.listener) this.listener.start(); //页面隐藏时相机帧的监听会自动停止,但恢复展示时不会自动启动,这里手动启动
  99. this.scan()
  100. },
  101. scan: function () {
  102. this.runningCrs = true;
  103. this.setData({
  104. showOverlay: false,
  105. showContent: false,
  106. selectType: SELECT_TYPE.NONE,
  107. });
  108. this.showLoading("识别中");
  109. },
  110. onCameraInit: function () {
  111. //找到canvas对象
  112. const query = wx.createSelectorQuery();
  113. query.select('#capture')
  114. .fields({node: true})
  115. .exec((res) => {
  116. const canvas = res[0].node;
  117. //设置canvas内部尺寸为480*640,frame-size="medium"的设置下相机帧大多是480*640
  118. canvas.width = 480;
  119. canvas.height = 640;
  120. this.canvas = canvas;
  121. this.crsClient = new CrsClient(this.data.config, this.canvas);
  122. //开始监听相机帧
  123. let cameraContext = wx.createCameraContext();
  124. this.listener = cameraContext.onCameraFrame(frame => {
  125. if (!this.canvas) return;
  126. let canvas = this.canvas;
  127. //如果尺寸不匹配,就修改canvas尺寸以适应相机帧
  128. if (canvas.width !== frame.width || canvas.height !== frame.height) {
  129. canvas.width = frame.width;
  130. canvas.height = frame.height;
  131. }
  132. this.queryImage(frame);
  133. });
  134. this.listener.start();
  135. });
  136. },
  137. queryImage: function (frame) {
  138. if (!this.runningCrs || this.busy || !this.crsClient) return;
  139. //最短的两次CRS请求间隔
  140. let now = new Date().getTime();
  141. if (this.last && (now - this.last < this.data.config.minInterval)) return;
  142. this.last = now;
  143. this.busy = true; //如果正在进行CRS请求,就不允许再次请求
  144. this.crsClient.queryImage(frame).then(res => {
  145. if (!this.runningCrs) return; //避免在停止后仍然触发
  146. let result = res.result;
  147. if (!result) return;
  148. if (result.target) {
  149. console.log("识别成功");
  150. this.runningCrs = false;
  151. this.hideLoading();
  152. let base64 = result.target.meta
  153. let web = this.base64_decode(base64)
  154. // 解析跳转链接
  155. wx.navigateTo({
  156. url: '../out/index?web=' + web + '&index=2',
  157. })
  158. // todo: 解析meta中的信息,触发业务逻辑
  159. //如果待触发的id列表中存在识别到的这个id,就触发
  160. if (this.data.targetIds.find(targetId => targetId === result.target.meta)) {
  161. this.onResult(result.target.meta);
  162. }
  163. } else {
  164. console.log("识别失败");
  165. }
  166. this.busy = false;
  167. }).catch(e => {
  168. this.busy = false;
  169. }); //小程序iOS端不支持finally,所以在then和catch里分别设置busy = false
  170. },
  171. onResult: function (target) {
  172. console.log("触发内容!");
  173. console.log(target);
  174. if (target) {
  175. console.log("meta base64:", target);
  176. }
  177. this.setData({
  178. showOverlay: false,
  179. showContent: true,
  180. selectType: SELECT_TYPE.IMAGE,
  181. });
  182. },
  183. //界面:
  184. back: function () {
  185. this.runningCrs = false;
  186. this.setData({
  187. showOverlay: true,
  188. showContent: false,
  189. selectType: SELECT_TYPE.NONE,
  190. });
  191. this.hideLoading();
  192. },
  193. experience: function () {
  194. this.setData({
  195. showOverlay: false,
  196. showContent: true,
  197. selectType: SELECT_TYPE.IMAGE,
  198. });
  199. },
  200. download: function () {
  201. wx.saveImageToPhotosAlbum({
  202. filePath: "/images/namecard.jpg",
  203. success: res => {
  204. wx.showToast({title: "已保存到相册", icon: "none"});
  205. },
  206. fail: res => {
  207. wx.showToast({title: "保存失败", icon: "none"});
  208. },
  209. });
  210. },
  211. selectContent: function (e) {
  212. this.setData({
  213. selectType: e.currentTarget.dataset.contenttype,
  214. });
  215. },
  216. queryToken: function() { // 获取token
  217. return new Promise((resolve, reject) => {
  218. wx.request({
  219. url: 'https://cktest.2weisou.com/meta/ar/ar/getToken',
  220. method: 'get',
  221. data: {},
  222. header: {
  223. 'content-type': 'application/json'
  224. },
  225. success: res => resolve(res.data),
  226. fail: err => reject(err)
  227. });
  228. });
  229. },
  230. base64_decode(input) { // 解码,配合decodeURIComponent使用
  231. var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  232. var output = "";
  233. var chr1, chr2, chr3;
  234. var enc1, enc2, enc3, enc4;
  235. var i = 0;
  236. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  237. while (i < input.length) {
  238. enc1 = base64EncodeChars.indexOf(input.charAt(i++));
  239. enc2 = base64EncodeChars.indexOf(input.charAt(i++));
  240. enc3 = base64EncodeChars.indexOf(input.charAt(i++));
  241. enc4 = base64EncodeChars.indexOf(input.charAt(i++));
  242. chr1 = (enc1 << 2) | (enc2 >> 4);
  243. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  244. chr3 = ((enc3 & 3) << 6) | enc4;
  245. output = output + String.fromCharCode(chr1);
  246. if (enc3 != 64) {
  247. output = output + String.fromCharCode(chr2);
  248. }
  249. if (enc4 != 64) {
  250. output = output + String.fromCharCode(chr3);
  251. }
  252. }
  253. return this.utf8_decode(output);
  254. },
  255. utf8_decode(utftext) { // utf-8解码
  256. var string = '';
  257. let i = 0;
  258. let c = 0;
  259. let c1 = 0;
  260. let c2 = 0;
  261. while (i < utftext.length) {
  262. c = utftext.charCodeAt(i);
  263. if (c < 128) {
  264. string += String.fromCharCode(c);
  265. i++;
  266. } else if ((c > 191) && (c < 224)) {
  267. c1 = utftext.charCodeAt(i + 1);
  268. string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
  269. i += 2;
  270. } else {
  271. c1 = utftext.charCodeAt(i + 1);
  272. c2 = utftext.charCodeAt(i + 2);
  273. string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
  274. i += 3;
  275. }
  276. }
  277. return string;
  278. }
  279. });