zhuapai.vue 12 KB

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