zhuapai.vue 12 KB

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