ImageCapture: takePhoto() 方法

ImageCapture 介面的 takePhoto() 方法使用影片捕獲裝置進行單次曝光,該裝置以 MediaStreamTrack 作為源,並返回一個 Promise,該 Promise 會解析為一個包含資料的 Blob

語法

js
takePhoto()
takePhoto(photoSettings)

引數

photoSettings 可選

用於設定待拍攝照片選項的物件。可用選項包括:

fillLightMode

捕獲裝置的閃光燈設定,可選值為 "auto""off""flash"

imageHeight

期望的影像高度(整數)。如果使用者代理僅支援離散的高度值,則會選擇最接近此設定的高度值。

imageWidth

期望的影像寬度(整數)。如果使用者代理僅支援離散的寬度值,則會選擇最接近此設定的寬度值。

redEyeReduction

一個布林值,指示是否應在可用時使用紅眼消除功能。

返回值

一個 Promise,它會解析為一個 Blob

異常

InvalidStateError DOMException

如果建構函式中傳入的 MediaStreamTrackreadyState 屬性不是 live,則丟擲此異常。

UnknownError DOMException

如果由於任何原因操作無法完成,則丟擲此異常。

示例

此示例摘自 Simple Image Capture 演示。它展示瞭如何使用 takePhoto() 返回的 Promise 將返回的 Blob 複製到一個 <img> 元素。為簡化起見,它沒有展示如何例項化 ImageCapture 物件。

js
let takePhotoButton = document.querySelector("button#takePhoto");
let canvas = document.querySelector("canvas");

takePhotoButton.onclick = takePhoto;

function takePhoto() {
  imageCapture
    .takePhoto()
    .then((blob) => {
      console.log("Took photo:", blob);
      img.classList.remove("hidden");
      img.src = URL.createObjectURL(blob);
    })
    .catch((error) => {
      console.error("takePhoto() error: ", error);
    });
}

規範

規範
MediaStream 影像捕獲
# dom-imagecapture-takephoto

瀏覽器相容性