Eggs Sunny Side Up
본문 바로가기
Web/JavaScript

[JS] 웹에 웹캠 거울버전으로 2개 영상 송출

by guswn100059 2023. 7. 19.

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="cpath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<link href="resources/css/main.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsmpeg/0.1/jsmpg.js"></script>
<title>메인페이지</title>
<style type="text/css">
#videoElement, #mirrored {
	width: 500px;
	height: 375px;
	background-color: #666;
  display: inline-block;
}
</style>
</head>
<body>

	<div class="videoPlayer">
		<video autoplay="true" id="videoElement"></video>
      	<canvas class="canvas" id="mirrored"></canvas>
	</div>

	<script type="text/javascript" src="resources/JS/webCam.js"></script>

	

</body>
</html>

 

js

/**
 * 
 */

document.addEventListener("DOMContentLoaded", () => {
  new App();
})

class App {
  constructor() {

    const video = document.querySelector("#videoElement");

    if (navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then( (stream) => { // function 의 this와 화살표 함수의 this 가 다름
          video.srcObject = stream;
        })
        .catch(function (error) {
          console.log("Something went wrong!");
          console.log(error);
          return;
        });
    }

    video.addEventListener( "loadedmetadata", () => {
      window.requestAnimationFrame(this.draw.bind(this));
    });
  }

  draw(t) {

    window.requestAnimationFrame(this.draw.bind(this));
    
    const canvas = document.querySelector("#mirrored");
    const video = document.querySelector("#videoElement");
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    const ctx = canvas.getContext('2d');
    ctx.translate(video.videoWidth, 0);
    ctx.scale(-1,1);
    ctx.drawImage(video, 0, 0, 
    	video.videoWidth, 
        video.videoHeight);  
    
  }
}


참고 블로그

https://velog.io/@davelee/browser%EC%97%90%EC%84%9C-webcam-%EC%9D%B4%EC%9A%A9%ED%95%98%EA%B8%B0

댓글