zhuapai.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <template>
  2. <view class="zhuapai-drop-container" id="Drop" ref="DropRef" :style="style" @touchmove="touchmove($event)"
  3. @touchstart="touchstart($event)">
  4. <view class="phone-camera-box-zhuapai">
  5. <camera class="camera" device-position="front" flash="off" style="width: 200px;height: 200px"
  6. :class="myClass" @initdone="onVideoSuccess" @error="handleError" @stop="handleStop"></camera>
  7. <!-- 用于抓拍切出去传递固定img-->
  8. <img :src="imgUrl" alt="" v-show="false">
  9. </view>
  10. <view v-show="showVideo" @click="noShowVideoBtn" class="shiti-video-hidden-btn">
  11. <icon :style="{ backgroundImage: 'url(' + iconsArr.videoCloseIcon + ')' }"></icon>
  12. </view>
  13. <view v-show="!showVideo" @click="showVideoBtn" class="shiti-video-show-btn">
  14. <icon :style="{ backgroundImage: 'url(' + iconsArr.videoPlayIcon + ')' }"></icon>
  15. </view>
  16. <canvas canvas-id="frameCanvas" id="frameCanvas"
  17. style="position: absolute;top:9999px;left: 0px;width: 100vw; height: 100vh;z-index:-2"></canvas>
  18. </view>
  19. </template>
  20. <script setup>
  21. import {
  22. ref,
  23. onUnmounted,
  24. nextTick,
  25. computed,
  26. onMounted,
  27. reactive,
  28. getCurrentInstance
  29. } from "vue";
  30. import cacheManager from '@/utils/cacheManager.js';
  31. import * as ksApi from "@/api/kaoshi.js"
  32. import {
  33. getStaticUrl
  34. } from "@/utils/common.js"
  35. import {
  36. useZhuapaiStore
  37. } from "@/store/zhuapai.js"
  38. import {
  39. getFileUpload
  40. } from "@/api/kaoshi.js"
  41. const zhuapaiStore = useZhuapaiStore();
  42. const imgUrl = '';
  43. const cameraContext = ref(null);
  44. // 响应式数据
  45. const frameListener = ref(null)
  46. const isCapturing = ref(false)
  47. const capturedImage = ref('')
  48. const currentFrame = ref(null) // 存储当前帧数据
  49. const myInstanceR = getCurrentInstance()
  50. const DropRef = ref(null);
  51. const DropContainerRef = ref(null);
  52. const zhuapai = ref(0); // 单位分
  53. const operId = ref(null); // 单位分
  54. const disX = ref(0); // 移动x
  55. const disY = ref(0); // 移动y
  56. const showVideo = ref(true);
  57. const isBuffer = ref(false);
  58. const stopTimer = ref(null);
  59. const style = ref({
  60. top: "17vh",
  61. right: "0",
  62. });
  63. const iconsArr = reactive({
  64. noKaoshiImg: '',
  65. videoCloseIcon: '',
  66. videoPlayIcon: '',
  67. })
  68. const myClass = computed(() => {
  69. return {
  70. 'show-video': showVideo.value,
  71. 'hidden-video': !showVideo.value
  72. }
  73. })
  74. const emits = defineEmits(['init', 'success', 'error', 'cancel', 'progress'])
  75. let timer1 = null;
  76. let timer2 = null;
  77. function noShowVideoBtn() {
  78. showVideo.value = false
  79. }
  80. function showVideoBtn() {
  81. showVideo.value = true;
  82. }
  83. function touchmove(event) {
  84. // 2,获取手指移动的实时位置 需要减去位置差
  85. let moveX = event.touches[0].pageX - disX.value;
  86. let moveY = event.touches[0].pageY - disY.value;
  87. const systemInfo = uni.getAppBaseInfo();
  88. const windowHeight = systemInfo.windowHeight; // 可视区域高度 ‌:ml-citation{ref="1,3" data="citationList"}
  89. const windowWidth = systemInfo.windowWidth; // 可视区域高度 ‌:ml-citation{ref="1,3" data="citationList"}
  90. // 3,获取容器的宽高和拖动元素的宽高 每一次移动都会获取一次 ,建议放在外面进行获取
  91. // let dragHeight = DropRef.value.$el.offsetHeight;
  92. // let dragWidth = DropRef.value.$el.offsetWidth;
  93. let dragHeight = 0;
  94. let dragWidth = 0;
  95. // 4,控制范围:在元素 被拖拽的过程中 判断 元素的定位值 是否到达边界 如果到了 就不能在走了
  96. if (moveX <= 0) {
  97. moveX = 0;
  98. }
  99. // 上边界
  100. if (moveY <= 0) {
  101. moveY = 0;
  102. }
  103. //下边界 容器高度 - 拖动元素高度
  104. if (moveY >= windowHeight - dragHeight - 150) {
  105. moveY = windowHeight - dragHeight - 150;
  106. }
  107. //右边界 容器宽度 - 拖动元素宽度
  108. if (moveX >= windowWidth - dragWidth) {
  109. moveX = 0;
  110. }
  111. // 5,开始移动
  112. style.value.top = moveY + "px";
  113. }
  114. function touchstart(event) {
  115. // disX.value = event.touches[0].pageX - DropRef.value.$el.offsetLeft;
  116. // disY.value = event.touches[0].pageY - DropRef.value.$el.offsetTop;
  117. disX.value = 0;
  118. disY.value = 0;
  119. }
  120. function init(options) {
  121. zhuapai.value = options.zhuapai;
  122. operId.value = options.operId;
  123. if (zhuapai.value > 0) {
  124. // 启动摄像头
  125. nextTick(() => {
  126. startCamera()
  127. // 设定计时器
  128. console.log('抓拍设定', zhuapai.value)
  129. timer2 = setInterval(() => {
  130. handleZhua()
  131. }, zhuapai.value * 60 * 1000)
  132. })
  133. }
  134. }
  135. function startCamera() {
  136. // 请求摄像头权限并获取流
  137. cameraContext.value = uni.createCameraContext();
  138. startFrameListener()
  139. }
  140. function urlToBase64(url) {
  141. return new Promise((resolve, reject) => {
  142. // #ifdef MP-WEIXIN
  143. // 微信小程序平台
  144. uni.getFileSystemManager().readFile({
  145. filePath: url, // 图片临时路径
  146. encoding: 'base64', // 指定编码格式
  147. success: (res) => {
  148. // 拼接Data URL前缀,注意图片类型可能需要根据实际情况调整(如png)
  149. let base64 = 'data:image/jpeg;base64,' + res.data;
  150. resolve(base64);
  151. },
  152. fail: (err) => {
  153. reject(err);
  154. }
  155. });
  156. // #endif
  157. });
  158. }
  159. function getSnapShotImage(data) {
  160. console.log('转转图片成base64')
  161. urlToBase64(data).then((d1) => {
  162. const imgData = d1.split(';base64,');
  163. if (!imgData.length) {
  164. console.error('【源 :拍照数据异常,未找到图片二进制数据分割节点: `;base64,`】');
  165. return;
  166. }
  167. const opt = {
  168. data: imgData[1],
  169. prefix: 'kaoshi/zhuapai',
  170. suffix: 'png',
  171. };
  172. console.log('上传图片')
  173. getFileUpload(opt).then(res => {
  174. const dOption = {
  175. operId: operId.value,
  176. url: res.data
  177. }
  178. ksApi.getClientZhuaPaiUpdate(dOption)
  179. .then(res => {
  180. console.log('【源 : 获取抓拍数据】');
  181. // 抓拍成功 继续监听
  182. frameListener.value.start()
  183. })
  184. .catch(err => {
  185. console.error('源 :抓拍接口异常', err);
  186. uni.showToast({
  187. icon: 'none',
  188. title: '抓拍图片异常!'
  189. })
  190. uni.redirectTo({
  191. url: "/pages/client/Kaoshi/list"
  192. })
  193. });
  194. }).catch(err => {
  195. uni.showToast({
  196. icon: 'none',
  197. title: '当前网络可能存在异常,请稍后重试,如持续异常,请联系管理员。注:若异常未联系管理员,可能会影响考试结果。'
  198. })
  199. uni.redirectTo({
  200. url: "/pages/client/Kaoshi/list"
  201. })
  202. })
  203. })
  204. }
  205. function doZhuaiPai(ImageFile) {
  206. try {
  207. if (zhuapaiStore.status == 0) {
  208. getSnapShotImage(ImageFile);
  209. } else {
  210. const ImageFile1 = imgUrl.value;
  211. getSnapShotImage(ImageFile1);
  212. }
  213. } catch (err) {
  214. console.error('源 :绘图失败', err);
  215. }
  216. }
  217. function handleZhua() {
  218. console.log('抓拍')
  219. captureSilently();
  220. }
  221. function onVideoSuccess() {
  222. /* setTimeout(() => {
  223. // 首次运行进行抓拍一次
  224. handleZhua();
  225. }, 3000);*/
  226. }
  227. function onVideoError() {
  228. emits('error')
  229. }
  230. function handleError() {
  231. emits('error')
  232. }
  233. function handleStop() {
  234. emits('error')
  235. }
  236. // 针对视频通话的监听处理
  237. function onTimeupdate() {
  238. if (isBuffer.value) {
  239. console.log('buffer')
  240. return;
  241. }
  242. if (!stopTimer.value) {
  243. return;
  244. }
  245. console.log('onTimeupdate')
  246. clearTimeout(stopTimer.value);
  247. stopTimer.value = null;
  248. }
  249. function onProgress() {
  250. if (stopTimer.value) {
  251. return;
  252. }
  253. isBuffer.value = true;
  254. console.log('onProgress')
  255. // buffer时间增大到3秒 过滤掉后续的onTimeupdate
  256. timer1 = setTimeout(() => {
  257. isBuffer.value = false
  258. }, 3000)
  259. // 视频中途暂停被占用
  260. stopTimer.value = setTimeout(() => {
  261. emits('progress', false);
  262. console.log('结束')
  263. }, 10 * 1000)
  264. }
  265. /******************************************************/
  266. // 开始监听相机帧数据
  267. function startFrameListener() {
  268. if (!cameraContext.value) {
  269. uni.showToast({
  270. title: '相机未初始化',
  271. icon: 'none'
  272. })
  273. return
  274. }
  275. frameListener.value = cameraContext.value.onCameraFrame((frame) => {
  276. // 存储当前帧数据,用于后续抓拍
  277. currentFrame.value = frame
  278. // console.log('接收帧数据:', frame.width, frame.height)
  279. })
  280. frameListener.value.start()
  281. isCapturing.value = true
  282. // uni.showToast({ title: '开始监控帧数据', icon: 'success' })
  283. }
  284. // 停止监听帧数据
  285. function stopFrameListener() {
  286. if (frameListener.value) {
  287. frameListener.value.stop()
  288. frameListener.value = null
  289. }
  290. isCapturing.value = false
  291. // uni.showToast({ title: '已停止监控', icon: 'success' })
  292. }
  293. // 静音抓拍核心函数
  294. async function captureSilently() {
  295. if (!isCapturing.value || !currentFrame.value) {
  296. uni.showToast({
  297. title: '请先开始监控帧数据',
  298. icon: 'none'
  299. })
  300. return
  301. }
  302. try {
  303. console.log('停止前')
  304. // 临时停止监听以避免数据冲突
  305. stopFrameListener()
  306. console.log('开始绘制', )
  307. // 将帧数据绘制到Canvas并导出为图片
  308. await drawFrameToCanvas(currentFrame.value).then(url => {
  309. console.log('获取地址')
  310. getSnapShotImage(url)
  311. })
  312. // 重新开始监听
  313. startFrameListener()
  314. } catch (error) {
  315. console.log('errrrr', error)
  316. handleError();
  317. }
  318. }
  319. // 将帧数据绘制到Canvas
  320. function drawFrameToCanvas(frame) {
  321. return new Promise((resolve, reject) => {
  322. try {
  323. // 确保有有效的帧数据
  324. if (!frame || !frame.data || !frame.width || !frame.height) {
  325. reject(new Error('无效的帧数据'))
  326. return
  327. }
  328. // 将ArrayBuffer转换为Uint8ClampedArray[4](@ref)
  329. const dataArray = new Uint8Array(frame.data)
  330. const clampedArray = new Uint8ClampedArray(dataArray)
  331. console.log('clampedArray', clampedArray.length)
  332. // 使用wx.canvasPutImageData将帧数据绘制到Canvas[4](@ref)
  333. wx.canvasPutImageData({
  334. canvasId: 'frameCanvas',
  335. data: clampedArray,
  336. x: 0,
  337. y: 0,
  338. width: frame.width,
  339. height: frame.height,
  340. success: () => {
  341. // 绘制成功后,将Canvas内容转换为临时图片文件
  342. wx.canvasToTempFilePath({
  343. canvasId: 'frameCanvas',
  344. destWidth: frame.width,
  345. destHeight: frame.height,
  346. fileType: 'png',
  347. quality: 0.7,
  348. success: (res) => {
  349. capturedImage.value = res.tempFilePath
  350. resolve(res.tempFilePath)
  351. },
  352. fail: (err) => {
  353. console.log('5555', err)
  354. reject(new Error(`生成图片失败: ${err.errMsg}`))
  355. }
  356. }, myInstanceR.proxy)
  357. },
  358. fail: (err) => {
  359. console.log('6666', err)
  360. reject(new Error(`绘制到Canvas失败: ${err.errMsg}`))
  361. }
  362. }, myInstanceR.proxy)
  363. } catch (err) {
  364. console.log('ccccc', err)
  365. }
  366. })
  367. }
  368. /******************************************************/
  369. onMounted(() => {
  370. iconsArr.videoCloseIcon = cacheManager.get('projectImg').video_close_icon;
  371. iconsArr.videoPlayIcon = cacheManager.get('projectImg').video_play_icon;
  372. });
  373. onUnmounted(() => {
  374. stopFrameListener()
  375. if (timer1) {
  376. clearTimeout(timer1);
  377. timer1 = null;
  378. }
  379. if (stopTimer.value) {
  380. clearTimeout(stopTimer.value);
  381. stopTimer.value = null;
  382. }
  383. if (timer2) {
  384. clearTimeout(timer2);
  385. timer2 = null;
  386. }
  387. })
  388. defineExpose({
  389. init,
  390. showVideoBtn,
  391. stopFrameListener
  392. })
  393. </script>
  394. <style lang="scss">
  395. .zhuapai-drop-container {
  396. width: 180rpx;
  397. height: 400rpx;
  398. margin: 0;
  399. padding: 0;
  400. z-index: 10;
  401. position: absolute;
  402. overflow: hidden;
  403. .phone-camera-box-zhuapai {
  404. width: 100%;
  405. height: 240rpx;
  406. position: absolute;
  407. overflow: hidden;
  408. .uni-video-container {
  409. background-color: transparent;
  410. pointer-events: none;
  411. }
  412. .canvas-view-box,
  413. .hidden-video {
  414. transform: translateY(10000rpx);
  415. }
  416. }
  417. .video-view-box {
  418. width: 100%;
  419. height: 240rpx;
  420. position: absolute;
  421. }
  422. .shiti-video-hidden-btn,
  423. .shiti-video-show-btn {
  424. position: absolute;
  425. top: 0;
  426. icon {
  427. width: 32rpx;
  428. height: 32rpx;
  429. display: block;
  430. background-size: cover;
  431. background-repeat: no-repeat;
  432. background-position: center;
  433. }
  434. }
  435. .shiti-video-hidden-btn {
  436. width: 60rpx;
  437. height: 60rpx;
  438. left: 0;
  439. icon {
  440. margin: 6rpx auto 6rpx 6rpx;
  441. }
  442. }
  443. .shiti-video-show-btn {
  444. background-color: #dcfbf1;
  445. padding: 20rpx;
  446. border-radius: 8rpx;
  447. right: 0;
  448. }
  449. }
  450. </style>