LoginSignup
2
3

More than 3 years have passed since last update.

IonicのAngularでWebRTCなカメラ取得して画像を切り出しQR読み取り

Last updated at Posted at 2020-06-25

カメラ取得してQR読み取りを目標にカメラ画像を切り出してQRへ投げたかったので自作で用意を思案。。
要所のみ記載なので流れメモになってます

Videoタグ設定

<video #video autoplay muted playsinline"></video>

Videoタグにカメラデータを流し込み

videoの設定でいろいろ変えられます
https://developer.mozilla.org/ja/docs/Web/API/Media_Streams_API/Constraints

deviceIdは無くても動作確認はできそう「facingMode: 'environment'」設定すればスマホは背面カメラ指定


const elmVideo = this.video.nativeElement;
navigator.mediaDevices
  .getUserMedia({
    video: {
      width: { min: 160, ideal: 320, max: 640 },
      height: { min: 120, ideal: 240 },
      aspectRatio: 1.777777778,
      frameRate: { max: 30 },
      facingMode: 'environment',
      deviceId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    },
  })
  .then((stream: MediaStream) => {
    elmVideo.srcObject = stream;
    // elmVideo.setAttribute('playsinline', true);
    elmVideo.play();
  })
  .catch((err: MediaStreamError) => {
    console.log(err);
  });

VideoタグのデータをCanvasへ書き込み

videoタグはwidthやheight指定してないで、ロードした映像のサイズを取得でCanvasサイズを指定

const elmVideo = this.video.nativeElement;
const elmCanvas = this.canvas.nativeElement;
elmCanvas.width = elmVideo.videoWidth;
elmCanvas.height = elmVideo.videoHeight;

const context2d = elmCanvas.getContext('2d');
context2d.drawImage(elmVideo, 0, 0, elmCanvas.width, elmCanvas.height);

画像の切り出しとQR読みと入へ譲渡

const elmCanvas = this.canvas.nativeElement;
const context2d = elmCanvas.getContext('2d');
const imageData = context2d.getImageData(x, y, width, height);

const code = jsQR(imageData.data, imageData.width, imageData.height, {
 inversionAttempts: 'dontInvert',
});

参考サイト

JavaScriptで自動再生のvideoを埋め込む時の注意点
http://cly7796.net/wp/javascript/precautions-for-embedding-autoplay-video-with-javascript/
★video要素、audio要素をJavaScriptから操作する
http://www.htmq.com/video/
開発者向けのウェブ技術See Web APISee Media Capture and Streams API (Media Streams)能力、制約、そして設定
https://developer.mozilla.org/ja/docs/Web/API/Media_Streams_API/Constraints

2
3
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
2
3