react 打開裝置相機鏡頭拍照,並儲存照片

網頁需要用到相機的場景還滿多的,像是身份驗證需要拍證件照上傳、發文、留言,是很基本的網頁應用。

這邊是用react來示範,原理大致上是會有以下幾個步驟:

  1. 打開相機
  2. 拍照顯示在畫面上

打開相機

要打開裝置相機,javascript有直接可以使用的原生api,但是要看到拍攝的螢幕,就要把相機的影像投射到video標籤上

這邊多穿插一個步驟,因為我們確定了影片、照片的尺寸,所以widthheight會先存在常數裡。

import { useRef, useState } from "react";

//...
const width = 300;
const height = 400;
const cameraRef = useRef(null);
const handleOpenCamera = () => {
  navigator.mediaDevices
    .getUserMedia({
      video: {
        width,
        height,
        audio: false,
        deviceId: "default",
        facingMode: "user",
      },
    })
    .then((stream) => {
      let video = cameraRef.current;
      video.srcObject = stream;
      video.play();
    })
    .catch((err) => {
      console.error("error:", err);
    });
};
<video ref={cameraRef}></video>
<button onClick={handleOpenCamera}>打開相機</button>

facingMode我用user,會打開前置境頭;這時候你會發現他的成像是左右相反的,也就是說如果你的臉往右轉,網頁上會變成左轉,所以我們加上一行css來修正這個問題。

video {
  transform: rotateY(180deg);
}

 

拍照顯示在畫面上

首先要顯示圖片的地方,我們用canvas來放。

const photoRef = useRef(null);
const handleTakePhoto = () => {
    const target = photoRef.current;
    const ctx = target.getContext("2d");
    target.width = width;
    target.height = height;
    ctx.translate(width, 0);
    ctx.scale(-1, 1);
    ctx.drawImage(cameraRef.current, 0, 0, width, height);
};
<canvas ref={photoRef} width={width} height={height}></canvas>
<button onClick={handleTakePhoto}>拍照</button>

  

1+

| 軟體開發 | 網站建置 | 網頁系統 | 資料庫網站 |

| 客製化網站 (報名系統、投票系統、掛號系統...) |

| 前後端技術合作 |

加入Line立即聊聊:@539mjyid

0 回復

發表評論

想要加入討論嗎?
請盡情發表您的想法!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。