首页 > 解决方案 > 如何将网络摄像头捕获的图像放入输入文件

问题描述

我正在尝试从网络摄像头上传图像,但我不确定如何将捕获的图像分配到输入文件字段中。这是代码:

<input type="file" id="document">

<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>

我必须将画布图像放入我的输入文件字段id="document"

const player = document.getElementById('player');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
  
const constraints = {
   video: true,
};
  
captureButton.addEventListener('click', (e) => {
   context.drawImage(player, 0, 0, canvas.width, canvas.height);
   e.preventDefault();
 });
  
navigator.mediaDevices.getUserMedia(constraints)
 .then((stream) => {
  player.srcObject = stream;
 });

标签: javascripthtmlcapture

解决方案


要从用户的相机捕获图像,您可以使用设置为用户的捕获属性。

像这样:

<label for="theImageFile">Upload photo from live camera:</label>
<input type="file" id="theImageFile" capture="user" accept="image/*">

在此处阅读有关它的更多信息:https ://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture


推荐阅读