|
- import {CrsClient} from "./crsClient";
- import {CryptoJS} from "./CryptoJS";
-
- const systemInfo = wx.getSystemInfoSync();
-
- const SELECT_TYPE = {
- NONE: 0,
- IMAGE: 1,
- VIDEO: 2,
- };
-
- Page({
- data: {
- showOverlay: true,
- showSelect: false,
- SELECT_TYPE: SELECT_TYPE,
- selectType: 0,
-
- //CRS配置
- config: {
- apiKey: 'a9abd99b2dfb3a5bee964cbb0bced0ae', // EasyAR开发中心 - API KEY - API Key
- apiSecret: '483e000a38265687c058efb7ab66cbc0917a3331b6dbf5482df46c76cb749529', // EasyAR开发中心 - API KEY - API Secret
- crsAppId: '8911f4b8f03725e300ca4130c01f27e9', // EasyAR开发中心 - 云服务 - 云识别管理 - 云识别库信息 - CRS AppId
- token: '',
- clientHost: 'https://bd9b3490fe845642e600cf53f0cd64b8.cn1.crs.easyar.com:8443', //服务器一般不变
- jpegQuality: 0.7, //JPEG压缩质量,建议不低于70%
- minInterval: 1000, //最短的两次CRS请求间隔
- },
- //识别到这个数组中的ID就触发内容
- targetIds: [
- "6c27e0a1-e4ca-424d-9062-4c8ec676a5ad",
- "ec72a9a2-20d5-4b86-82db-05f29e1c0fbb",
- "f0bdba05-e610-4d1c-811a-5034ccc0d1f7",
- "79014ee9-60c7-4a0c-81ed-0d5889a7ecc9"
- ],
- showLoading: false,
- showLoadingText: "",
- },
- /** @type {CameraFrameListener} 相机帧回调 */
- listener: undefined,
- /** @type {HTMLCanvasElement} canvas对象 */
- canvas: undefined,
- /** @type {boolean} 是否需要持续识别,在点击“识别体验”之后和识别成功之前为true */
- runningCrs: undefined,
- /** @type {boolean} 当前是否正在进行CRS请求 */
- busy: undefined,
- /** @type {CrsClient} 负责发起CRS请求的对象 */
- crsClient: undefined,
- /** @type {number} 最后一次CRS请求的事件,用于判断是否满足最短请求间隔 */
- last: undefined,
-
- onLoad: function () {
- },
- onReady: function () {
- if (systemInfo.platform === "devtools") { //开发工具不会触发initdone事件,于是在onReady手动触发
- this.onCameraInit();
- }
-
- // 获取token
- this.queryToken().then(msg => {
- console.log('token1')
- console.log(msg)
- this.data.config.token = msg;
- }).catch(err => {
- console.info(err);
- });
- },
-
- showLoading(text) {
- this.setData({
- showLoading: true,
- showLoadingText: text,
- });
- },
- hideLoading() {
- this.setData({
- showLoading: false,
- });
- },
-
- //图像识别部分:
-
- onShow: function () {
- if (this.listener) this.listener.start(); //页面隐藏时相机帧的监听会自动停止,但恢复展示时不会自动启动,这里手动启动
- this.scan()
- },
- scan: function () {
- this.runningCrs = true;
- this.setData({
- showOverlay: false,
- showContent: false,
- selectType: SELECT_TYPE.NONE,
- });
- this.showLoading("识别中");
- },
- onCameraInit: function () {
- //找到canvas对象
- const query = wx.createSelectorQuery();
- query.select('#capture')
- .fields({node: true})
- .exec((res) => {
- const canvas = res[0].node;
- //设置canvas内部尺寸为480*640,frame-size="medium"的设置下相机帧大多是480*640
- canvas.width = 480;
- canvas.height = 640;
- this.canvas = canvas;
- this.crsClient = new CrsClient(this.data.config, this.canvas);
- //开始监听相机帧
- let cameraContext = wx.createCameraContext();
- this.listener = cameraContext.onCameraFrame(frame => {
- if (!this.canvas) return;
- let canvas = this.canvas;
- //如果尺寸不匹配,就修改canvas尺寸以适应相机帧
- if (canvas.width !== frame.width || canvas.height !== frame.height) {
- canvas.width = frame.width;
- canvas.height = frame.height;
- }
- this.queryImage(frame);
- });
- this.listener.start();
- });
- },
-
- queryImage: function (frame) {
- if (!this.runningCrs || this.busy || !this.crsClient) return;
- //最短的两次CRS请求间隔
- let now = new Date().getTime();
- if (this.last && (now - this.last < this.data.config.minInterval)) return;
- this.last = now;
- this.busy = true; //如果正在进行CRS请求,就不允许再次请求
- this.crsClient.queryImage(frame).then(res => {
- if (!this.runningCrs) return; //避免在停止后仍然触发
- let result = res.result;
- if (!result) return;
- if (result.target) {
- console.log("识别成功");
- this.runningCrs = false;
- this.hideLoading();
- let base64 = result.target.meta
- let web = this.base64_decode(base64)
- // 解析跳转链接
- wx.navigateTo({
- url: '../out/index?web=' + web + '&index=2',
- })
- // todo: 解析meta中的信息,触发业务逻辑
- //如果待触发的id列表中存在识别到的这个id,就触发
- if (this.data.targetIds.find(targetId => targetId === result.target.meta)) {
- this.onResult(result.target.meta);
- }
- } else {
- console.log("识别失败");
- }
- this.busy = false;
- }).catch(e => {
- this.busy = false;
- }); //小程序iOS端不支持finally,所以在then和catch里分别设置busy = false
- },
- onResult: function (target) {
- console.log("触发内容!");
- console.log(target);
- if (target) {
- console.log("meta base64:", target);
- }
- this.setData({
- showOverlay: false,
- showContent: true,
- selectType: SELECT_TYPE.IMAGE,
- });
- },
- //界面:
- back: function () {
- this.runningCrs = false;
- this.setData({
- showOverlay: true,
- showContent: false,
- selectType: SELECT_TYPE.NONE,
- });
- this.hideLoading();
- },
- experience: function () {
- this.setData({
- showOverlay: false,
- showContent: true,
- selectType: SELECT_TYPE.IMAGE,
- });
- },
- download: function () {
- wx.saveImageToPhotosAlbum({
- filePath: "/images/namecard.jpg",
- success: res => {
- wx.showToast({title: "已保存到相册", icon: "none"});
- },
- fail: res => {
- wx.showToast({title: "保存失败", icon: "none"});
- },
- });
- },
- selectContent: function (e) {
- this.setData({
- selectType: e.currentTarget.dataset.contenttype,
- });
- },
- queryToken: function() { // 获取token
- return new Promise((resolve, reject) => {
- wx.request({
- url: 'https://cktest.2weisou.com/meta/ar/ar/getToken',
- method: 'get',
- data: {},
- header: {
- 'content-type': 'application/json'
- },
- success: res => resolve(res.data),
- fail: err => reject(err)
- });
- });
- },
- base64_decode(input) { // 解码,配合decodeURIComponent使用
- var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var output = "";
- var chr1, chr2, chr3;
- var enc1, enc2, enc3, enc4;
- var i = 0;
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- while (i < input.length) {
- enc1 = base64EncodeChars.indexOf(input.charAt(i++));
- enc2 = base64EncodeChars.indexOf(input.charAt(i++));
- enc3 = base64EncodeChars.indexOf(input.charAt(i++));
- enc4 = base64EncodeChars.indexOf(input.charAt(i++));
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
- output = output + String.fromCharCode(chr1);
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
- }
- return this.utf8_decode(output);
- },
- utf8_decode(utftext) { // utf-8解码
- var string = '';
- let i = 0;
- let c = 0;
- let c1 = 0;
- let c2 = 0;
- while (i < utftext.length) {
- c = utftext.charCodeAt(i);
- if (c < 128) {
- string += String.fromCharCode(c);
- i++;
- } else if ((c > 191) && (c < 224)) {
- c1 = utftext.charCodeAt(i + 1);
- string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
- i += 2;
- } else {
- c1 = utftext.charCodeAt(i + 1);
- c2 = utftext.charCodeAt(i + 2);
- string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
- i += 3;
- }
- }
- return string;
- }
- });
|