0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】ブラウザでカメラを使用する

Last updated at Posted at 2020-05-26

ブラウザからデバイスのカメラを使用する場合。とりあえず記載しているのはカメラ1つの場合で、スマホやタブレットで前面/背面カメラがある場合は未調査。
撮影した画像はAPIに渡す想定で、base64エンコードするまで記載しています。

検証環境

  • Google Chrome バージョン: 81.0.4044.138

ソースコード

html
<video id="video">Video stream not available.</video>
<canvas id="canvas"></canvas>
<input type="button" onclick="onClickCaptureButton()" value="capture"></input>
javascript
const video  = document.getElementById('video');
const canvas = document.getElementById('canvas');

video.addEventListener('canplay', (event) => {
  canvas.setAttribute('width' , video.videoWidth);
  canvas.setAttribute('height', video.videoHeight);
}, false);

navigator.mediaDevices.getUserMedia({video:true, audio:false})
.then((stream) => {
  video.srcObject = stream;
  video.play();
})
.catch((err) => {
  console.log(err);
});

function onClickCaptureButton(event) {
  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);

  const base64Image = canvas.toDataURL('image/jpeg', 0.95)
  // <!-- ここに画像の処理を書く。APIをコールするなり、imgタグを埋め込むなり。。。 -->
}
0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?