11-18 19:33
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Programming / WebApp] Canvas에 웹캠 화면 출력 본문

Programming/Web App

[Programming / WebApp] Canvas에 웹캠 화면 출력

cinema4dr12 2016. 9. 18. 22:01

이번 글에서는 Canvas 태그에 웹캠 화면을 출력하는 방법을 알아보도록 하겠다.


[Project File Download]

canvas-webcam.zip


[webcam.html]

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Cam Video</title>
    <link rel="stylesheet" href="./stylesheets/main.css">
</head>
<body>
      <div class="booth">
          <video id="video" width="800" height="600" autoplay=""></video>
          <canvas id="canvas" width="800" height="600"></canvas>
      </div>
      <script src="./javascripts/video.js"></script>
</body>
</html>


[/stylesheets/main.css]

.booth {
  width: 800px;
  background: #ccc;
  border: 10px solid #ddd;
  margin: 0 auto;
}


[/javascripts/video.js]

(function() {
  
  var canvas = document.getElementById('canvas'),
  context = canvas.getContext('2d'),
  video = document.getElementById('video'),
  vendorUrl = window.URL || window.webkitURL;
  
  navigator.getMedia =  navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetuserMedia ||
  navigator.msGetUserMedia;
  
  navigator.getMedia({
    video: true,
    audio: false
  }, function(stream) {
    video.src = vendorUrl.createObjectURL(stream);
    video.play();
  }, function(error) {
    // an error occurred
  } );
  
  video.addEventListener('play', function() {
    draw( this, context, 1024, 768 );
  }, false );
  
  function draw( video, context, width, height ) {
    var image, data, i, r, g, b, brightness;
    
    context.drawImage( video, 0, 0, width, height );
    
    image = context.getImageData( 0, 0, width, height );
    data = image.data;
    
    for( i = 0 ; i < data.length ; i += 4 ) {
      r = data[i];
      g = data[i + 1];
      b = data[i + 2];
      brightness = ( r + g + b ) / 3;
      
      data[i] = data[i + 1] = data[i + 2] = brightness;
    }
    
    image.data = data;
    
    context.putImageData( image, 0, 0 );
    
    setTimeout( draw, 10, video, context, width, height );
  }
  
} )();


[Result]


Comments