纯HTML 调用摄像头 获取拍照后的图片的base64

纯HTML 调用摄像头 获取拍照后的图片的base64

直接上代码:

html 复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web USB Camera</title>
</head>
<body>

<video id="video" width="400" autoplay playsinline></video>
<br>
<button id="snap">拍照</button>
<br>
<img id="photo" style="margin-top:10px; width:400px;">
<br>

<!-- ✅ 新增:用于完整显示 Base64 -->
<textarea id="output" style="width:100%;height:200px;margin-top:10px;"></textarea>

<script>
  const video = document.getElementById("video");
  const photo = document.getElementById("photo");
  const snapBtn = document.getElementById("snap");
  const output = document.getElementById("output"); // ✅ 新增引用

  // 获取摄像头
  navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => {
      video.srcObject = stream;
    })
    .catch(err => {
      alert("无法访问摄像头: " + err);
    });

  // 拍照
  snapBtn.onclick = function() {
    const canvas = document.createElement("canvas");
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    const ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0);

    photo.src = canvas.toDataURL("image/png");

    // ✅ 新增:完整 Base64 放进 textarea
    output.value = photo.src;

    console.log("Base64 length:", photo.src.length);
  };
</script>

</body>
</html>

效果如下图所示:

可以验证一下base64 是否正常 访问网站:

https://remeins.com/index/app/base64img

相关推荐
八角丶2 分钟前
Node.js 异步上下文详解(实验驱动)
前端·node.js
用户2181697049305 分钟前
Flutter (二十五)视频播放
前端
半个落月5 分钟前
在浏览器里运行 DeepSeek-R1:推理、流式输出与停止生成(二)
前端·人工智能·react.js
绿岛之北6 分钟前
Electron 安全第四章: Preload 与 IPC
前端·electron
xiaominlaopodaren6 分钟前
three.js最小地图运行时(六): 地图运行时
javascript·gis·three.js
半个落月13 分钟前
在浏览器里运行 DeepSeek-R1:从 WebGPU 检测到模型加载(一)
前端·人工智能·react.js
小白勇闯网安圈13 分钟前
Vue 工程化开发:组件复用、插槽、项目结构与 ES6 模块化
javascript·vue.js·es6
八角丶14 分钟前
Node.js 事件循环详解(实验驱动)
前端·node.js
deli00700714 分钟前
汉诺塔益智小游戏:浏览器里说句话,码道 WebUI 一键生成+部署上线
前端·ai编程
用户21816970493016 分钟前
Flutter (二十四) 音频
前端