首页 > 解决方案 > javascript - 为带有背景的视频制作屏幕截图按钮

问题描述

我是 js 和 html 的新手,我有一张背景图片,上面有他的头被移除的字符。而不是头部,而是打开一个网络摄像头,供某人放置他的头部而不是角色。它工作正常,但我想添加一个按钮,让我可以选择一起捕获网络摄像头 + 背景(带有网络摄像头 + 人物背景中某人头部的图片)并将其保存到我的本地计算机。html2canvas 不适合我,因为它不能与 flash 一起使用。当我尝试我的代码时,它只为我节省了没有背景的网络摄像头的捕获。如果有人能帮助我,那就太好了,再次,非常感谢!到目前为止,这是我的代码:

<script>
const vid = document.querySelector('video');
navigator.mediaDevices.getUserMedia({video: true}) // request cam
.then(stream => {
  vid.srcObject = stream; // don't use createObjectURL(MediaStream)
  return vid.play(); // returns a Promise
})
.then(()=>{ // enable the button
  const btn = document.querySelector('button');
  btn.disabled = false;
  btn.onclick = e => {
    takeASnap()
    .then(download);
  };
})
.catch(e=>console.log('please use the fiddle instead'));

function takeASnap(){
  const canvas = document.createElement('canvas'); // create a canvas
  const ctx = canvas.getContext('2d'); // get its context
  canvas.width = vid.videoWidth; // set its size to the one of the video
  canvas.height = vid.videoHeight;
  ctx.drawImage(vid, 0,0); // the video
  return new Promise((res, rej)=>{
    canvas.toBlob(res, 'image/jpeg'); // request a Blob from the canvas
  });
}
function download(blob){
  // uses the <a download> to download a Blob
  let a = document.createElement('a'); 
  a.href = URL.createObjectURL(blob);
  a.download = 'screenshot.jpg';
  document.body.appendChild(a);
  a.click();
}</script>
<style>

#tv_container {
    width: 1920px; /* Adjust picture image width */
    height: 1080px; /* Adjust picture image height */
    position: relative;
}
#tv_container:after {
    content: '';
    display: block;
    background: url('images/edison.png') no-repeat top left transparent;
    width: 100%;
    height: 100%;
    left: 0px;
    top: 0px;
    position: absolute;
    z-index: 10;
}
#tv_container video {
    position: absolute;
    top: 150px; /* Adjust top position */
    left: 600px; /* Adjust left position */
    z-index: 5;
}
</style>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="Display Webcam Stream" name="title">
<title>newton</title>
  
</head>
  
<body>
<div id="tv_container">
<video id="vid"></video>
</div>
<button>take a snapshot</button>
</body>
</html>

标签: javascripthtmlcss

解决方案


推荐阅读