zhuapai.vue 12 KB

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