纯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

相关推荐
我是小趴菜5 分钟前
前端如何让图片、视频、pdf等文件在浏览器直接下载而非预览
前端
cg339 分钟前
开源项目自动化:用 GitHub Actions 让每个 Issue 都被温柔以待
前端
haierccc19 分钟前
Win7、2008R2、Win10、Win11使用FLASH的方法
前端·javascript·html
We་ct22 分钟前
LeetCode 50. Pow(x, n):从暴力法到快速幂的优化之路
开发语言·前端·javascript·算法·leetcode·typescript·
柠檬味的Cat25 分钟前
使用腾讯云COS作为WordPress图床的实践
前端·github·腾讯云
Hilaku28 分钟前
卷AI、卷算法、2026 年的前端工程师到底在卷什么?
前端·javascript·面试
非凡ghost30 分钟前
AIMP(音乐播放软件)
前端·windows·音视频·firefox
xiaotao13131 分钟前
Vite 完全学习指南
前端·vite·前端打包
军军君011 小时前
Three.js基础功能学习十五:智能黑板实现实例二
开发语言·前端·javascript·vue.js·3d·threejs·三维
IT枫斗者1 小时前
构建具有执行功能的 AI Agent:基于工作记忆的任务规划与元认知监控架构
android·前端·vue.js·spring boot·后端·架构