5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ChromeのImage Capture API を使ってJavascriptで写真撮影

Last updated at Posted at 2017-09-05

Image Capture API を使って写真撮影をしてみました

Image Capture API とは

Chrome 59 で追加されたカメラを操作するAPIです

デモ

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>

<div id="container" style="margin: auto;">
  <video id="video" autoplay width="320" height="320"></video>
  <canvas id="canvas" width="320" height="320"></canvas>
  <button onclick="takePhoto()">写真撮影!!</button>
</div>

</body>
<script>
let video  = document.getElementById('video')
let canvas = document.getElementById('canvas')
let imageCapture

window.onload = _ => {

  navigator.mediaDevices.getUserMedia({video: true})
  .then(mediaStream => {
    video.srcObject = mediaStream

    let videoTrack = mediaStream.getVideoTracks()[0]
    imageCapture = new ImageCapture(videoTrack)
  })

}

let takePhoto = _ => {
  imageCapture.takePhoto()
    .then(blob => createImageBitmap(blob))
    .then(imageBitmap => drawCanvas(canvas, imageBitmap))
}

/**
 * https://github.com/GoogleChrome/samples/blob/gh-pages/image-capture/grab-frame-take-photo.js 
 */ 
function drawCanvas(canvas, img) {
  canvas.width = getComputedStyle(canvas).width.split('px')[0];
  canvas.height = getComputedStyle(canvas).height.split('px')[0];
  let ratio  = Math.min(canvas.width / img.width, canvas.height / img.height);
  let x = (canvas.width - img.width * ratio) / 2;
  let y = (canvas.height - img.height * ratio) / 2;
  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
  canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
      x, y, img.width * ratio, img.height * ratio);
}

</script>
</html>

ImageCapture には takePhoto と grabFrame の2つの関数があるのですが
それぞれの違いがよくわからず・・・

公式デモ
https://googlechrome.github.io/samples/image-capture/

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?