VideoLocalWindow.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <template>
  2. <div class="videoContainer">
  3. <video
  4. ref="video"
  5. id="video"
  6. :width="1280"
  7. :height="800"
  8. autoplay
  9. muted
  10. playsinline
  11. ></video>
  12. <div id="timestamp" v-show="false">
  13. {{ datetimeData.date + " " + datetimeData.time }}
  14. </div>
  15. <canvas id="blurred-canvas" :width="1280" :height="800"></canvas>
  16. <!-- <el-button @click="startCamera">开启摄像头</el-button>
  17. <el-button @click="stopCamera" :disabled="!isCameraActive"
  18. >关闭摄像头</el-button
  19. > -->
  20. </div>
  21. </template>
  22. <script>
  23. /* eslint-disable */
  24. import * as tf from "@tensorflow/tfjs";
  25. import * as bodyPix from "@tensorflow-models/body-pix";
  26. import { GetPersonByFace, GetPersonByFaceBase64 } from "@/API/custom";
  27. import Dayjs from "dayjs";
  28. export default {
  29. props: {
  30. processStep: {
  31. type: String,
  32. require: true,
  33. },
  34. isUpload: {
  35. type: String,
  36. require: false,
  37. },
  38. cameraData: {
  39. type: Object,
  40. default: () => ({}),
  41. },
  42. },
  43. watch: {
  44. processStep: {
  45. handler(step) {
  46. if (step == 0 || step == 9) {
  47. this.startCamera();
  48. } else {
  49. this.stopCamera();
  50. }
  51. },
  52. deep: true,
  53. immediate: true,
  54. },
  55. isUpload: {
  56. handler(val) {
  57. console.log("上传子级开关", val);
  58. if (val) {
  59. this.uploadImage();
  60. } else {
  61. this.isUpload = false;
  62. }
  63. },
  64. deep: true,
  65. immediate: true,
  66. },
  67. },
  68. data() {
  69. return {
  70. isCameraActive: false,
  71. video: null,
  72. stream: null,
  73. captureInterval: null, // 新增定时器变量
  74. datetimeData: {
  75. date: Dayjs(new Date()).format("YYYY-MM-DD"),
  76. time: Dayjs(new Date()).format("HH:mm:ss"),
  77. week: Dayjs(new Date()).format("dddd"),
  78. },
  79. // BodyPix模型加载
  80. net: null,
  81. localModelPath: "/js/model/bodypix/model-stride16.json",
  82. // 修改默认值为 true,自动开启背景虚化
  83. showBlurred: true,
  84. loading: true,
  85. };
  86. },
  87. methods: {
  88. refreshTime() {
  89. let speed = 1000;
  90. let timer = null;
  91. let theNowTime = () => {
  92. // this.datePersonData.time = Dayjs(new Date()).format('HH:mm:ss')
  93. this.datetimeData.time = Dayjs(new Date()).format("HH:mm:ss");
  94. this.datetimeData.date = Dayjs(new Date()).format("YYYY-MM-DD");
  95. this.datetimeData.week = Dayjs(new Date()).format("dddd");
  96. };
  97. timer = setInterval(theNowTime, speed);
  98. this.$once("hook:beforeDestroy", () => {
  99. clearInterval(timer);
  100. timer = null;
  101. });
  102. },
  103. async loadBodyPix() {
  104. this.net = await bodyPix.load({ modelUrl: this.localModelPath });
  105. console.log("BodyPix模型加载返回", this.net);
  106. this.processVideoFrame();
  107. },
  108. async processVideoFrame() {
  109. // 确保 video 和 blurredCanvas 存在
  110. if (this.showBlurred && this.video && this.blurredCanvas) {
  111. try {
  112. const segmentation = await this.net.segmentPerson(this.video);
  113. const backgroundBlurAmount = 10;
  114. const edgeBlurAmount = 3;
  115. const flipHorizontal = false;
  116. bodyPix.drawBokehEffect(
  117. this.blurredCanvas,
  118. this.video,
  119. segmentation,
  120. backgroundBlurAmount,
  121. edgeBlurAmount,
  122. flipHorizontal
  123. );
  124. } catch (err) {
  125. console.error("处理视频帧时出错:", err);
  126. }
  127. }
  128. requestAnimationFrame(() => this.processVideoFrame());
  129. },
  130. async startCamera() {
  131. try {
  132. this.stream = await navigator.mediaDevices.getUserMedia({
  133. video: true,
  134. });
  135. this.video = document.getElementById("video");
  136. this.isCameraActive = true;
  137. if (this.video) {
  138. this.video.srcObject = this.stream;
  139. this.loading = false;
  140. this.loadBodyPix();
  141. } else {
  142. this.error = "未能找到视频元素,请检查 HTML 结构。";
  143. this.loading = false;
  144. }
  145. if (this.isUpload) {
  146. setTimeout(() => {
  147. this.uploadImage();
  148. }, 1000);
  149. } else {
  150. // 新增定时截图功能
  151. this.captureInterval = setInterval(() => {
  152. this.captureImage();
  153. console.log("截图上传");
  154. }, 2500);
  155. }
  156. } catch (err) {
  157. console.error("摄像头访问错误:", err);
  158. alert(`摄像头访问失败: ${err.message}`);
  159. this.loading = false;
  160. }
  161. },
  162. stopCamera() {
  163. if (this.stream) {
  164. this.stream.getTracks().forEach((track) => track.stop());
  165. this.isCameraActive = false;
  166. this.video.srcObject = null;
  167. this.stream = null;
  168. // 停止定时器
  169. if (this.captureInterval) {
  170. clearInterval(this.captureInterval);
  171. this.captureInterval = null;
  172. }
  173. }
  174. },
  175. async captureImage() {
  176. if (this.video.paused) return;
  177. const canvas = document.createElement("canvas");
  178. const cropWidth = this.video.videoWidth * 0.5;
  179. const cropHeight = this.video.videoHeight * 0.98;
  180. // 设置canvas尺寸为选择区域大小
  181. canvas.width = cropWidth;
  182. canvas.height = cropHeight;
  183. const x = (this.video.videoWidth - cropWidth) / 2;
  184. const y = (this.video.videoHeight - cropHeight) / 2;
  185. const ctx = canvas.getContext("2d");
  186. //中心60%区域
  187. ctx.drawImage(
  188. this.video,
  189. x,
  190. y,
  191. cropWidth,
  192. cropHeight,
  193. 0,
  194. 0,
  195. cropWidth,
  196. cropHeight
  197. );
  198. // canvas.width = video.videoWidth;
  199. // canvas.height = video.videoHeight;
  200. // const ctx = canvas.getContext("2d");
  201. // ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  202. try {
  203. const base64Data = canvas.toDataURL("image/png");
  204. // console.log("上传数据:Base64", base64Data);
  205. // 替换YOUR_SERVER_URL为你的实际服务器地址
  206. const response = await fetch(
  207. "/yapi/System/Person/GetPersonByFaceBase64",
  208. {
  209. method: "POST",
  210. headers: {
  211. token: localStorage.getItem("token"),
  212. "Content-Type": "application/json",
  213. },
  214. body: JSON.stringify({
  215. data: base64Data,
  216. fileModule: 2,
  217. }),
  218. }
  219. );
  220. const result = await response.json();
  221. // console.log("上传反馈", response, result);
  222. if (result.code === 20000) {
  223. // console.log("服务器返回数据:", result);
  224. this.$emit("output", result.data);
  225. this.uploadImage();
  226. // setTimeout(() => {
  227. // this.stopCamera();
  228. // }, 200);
  229. }
  230. } catch (err) {
  231. console.error("上传过程中出错:", err);
  232. }
  233. },
  234. async uploadImage() {
  235. const canvas = document.createElement("canvas");
  236. const cropWidth = this.video.videoWidth * 0.5;
  237. const cropHeight = this.video.videoHeight * 0.98;
  238. // 设置canvas尺寸为选择区域大小
  239. canvas.width = cropWidth;
  240. canvas.height = cropHeight;
  241. const x = (this.video.videoWidth - cropWidth) / 2;
  242. const y = (this.video.videoHeight - cropHeight) / 2;
  243. const ctx = canvas.getContext("2d");
  244. // console.log(
  245. // "???????????????????",
  246. // x,
  247. // y,
  248. // cropWidth,
  249. // cropHeight,
  250. // this.video,
  251. // this.blurredCanvas,
  252. // canvas
  253. // );
  254. //中心60%区域-原图
  255. // ctx.drawImage(
  256. // this.video,
  257. // x,
  258. // y,
  259. // cropWidth,
  260. // cropHeight,
  261. // 0,
  262. // 0,
  263. // cropWidth,
  264. // cropHeight
  265. // );
  266. // 虚化背景处理绘制
  267. ctx.drawImage(
  268. this.showBlurred ? this.blurredCanvas : this.video,
  269. this.blurredCanvas.width * 0.25,
  270. this.blurredCanvas.height * 0.01,
  271. this.blurredCanvas.width * 0.5,
  272. this.blurredCanvas.height * 0.98,
  273. 0,
  274. 0,
  275. cropWidth,
  276. cropHeight
  277. );
  278. // ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  279. const timestampDiv = document.getElementById("timestamp");
  280. // 在canvas上绘制时间戳
  281. ctx.font = "24px Arial";
  282. ctx.fillStyle = "white";
  283. ctx.fillText(timestampDiv.textContent, 20, canvas.height - 20);
  284. try {
  285. const base64Data = canvas.toDataURL("image/png");
  286. // console.log("上传数据:Base64", base64Data);
  287. // 替换YOUR_SERVER_URL为你的实际服务器地址
  288. const response = await fetch("/yapi/File/UploadBase64", {
  289. method: "POST",
  290. headers: {
  291. token: localStorage.getItem("token"),
  292. "Content-Type": "application/json",
  293. },
  294. body: JSON.stringify({
  295. data: base64Data,
  296. fileModule: 1,
  297. }),
  298. });
  299. const result = await response.json();
  300. // console.log("上传反馈", response, result);
  301. if (result.code === 20000) {
  302. console.log("服务器上传返回数据:", result);
  303. this.$emit("outputPath", result.data);
  304. setTimeout(() => {
  305. this.stopCamera();
  306. }, 200);
  307. }
  308. this.isUpload = false;
  309. } catch (err) {
  310. console.error("上传过程中出错:", err);
  311. }
  312. },
  313. },
  314. mounted() {
  315. if (this.loading) {
  316. this.blurredCanvas = document.getElementById("blurred-canvas");
  317. if (this.blurredCanvas) {
  318. this.ctx = this.blurredCanvas.getContext("2d");
  319. }
  320. }
  321. },
  322. created() {
  323. this.startCamera();
  324. this.refreshTime();
  325. },
  326. beforeDestroy() {
  327. this.stopCamera();
  328. },
  329. };
  330. </script>
  331. <style scoped>
  332. .videoContainer {
  333. position: relative;
  334. width: 50%; /* 容器宽度设为50% */
  335. height: 100%; /* 容器高度设为100% */
  336. margin: 0 auto; /* 居中显示 */
  337. overflow: hidden; /* 隐藏溢出部分 */
  338. }
  339. video {
  340. height: 800px;
  341. width: 1280px;
  342. transform: translate(-25%, 0%);
  343. /* width: 100%;
  344. max-width: 500px; */
  345. background: #000;
  346. }
  347. #timestamp {
  348. position: absolute;
  349. bottom: 20px;
  350. left: 20px;
  351. color: white;
  352. font-size: 24px;
  353. background-color: rgba(0, 0, 0, 0.5);
  354. padding: 5px;
  355. }
  356. #blurred-video {
  357. display: none;
  358. }
  359. </style>