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つの関数があるのですが
それぞれの違いがよくわからず・・・