如何在视频HTML5上保存用于保存图像的按钮

时间:2016-06-26 19:24:46

标签: javascript html5

在HTML5视频中,我们可以右键单击视频并选择“将图像另存为...”

我想制作一个按钮来自动保存图像

请帮忙,谢谢

1 个答案:

答案 0 :(得分:0)

你需要一个canvas元素,可以使用drawImage(videoelement,0,0,videowidth,videoheigth)(与视频一样大的画布)绘制视频数据,然后使用canvas.toDataURL();这将给你一个在画布中框架的base64 png图像然后将数据转换为blob,这样你就可以保存它,然后你只需要使blob成为一个网址,打开网址就可以保存它

实施例

var v = document.getElementById("video1");
var canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var interval;

function canvasdrawvideo() {
  ctx.drawImage(v, 0, 0, 270, 135);
}

function savecanvasimage(fileName) {
  var dataURL = canvas.toDataURL("image/png");
  var data = atob(dataURL.substring("data:image/png;base64,".length)),
    asArray = new Uint8Array(data.length);
  for (var i = 0, len = data.length; i < len; ++i) {
    asArray[i] = data.charCodeAt(i);
  }
  var blob = new Blob([asArray.buffer], {
    type: "octet/stream"
  });

  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  var url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = fileName;
  a.click();
  window.URL.revokeObjectURL(url);
}

v.addEventListener("play", function() {
  interval = setInterval(canvasdrawvideo, 20);
});
v.addEventListener("pause", function() {
  clearInterval(interval);
}, false);
v.addEventListener("ended", function() {
  clearInterval(interval);
}, false);
<html>

<body>
  <p>Video to use:</p>
  <video id="video1" controls width="270" autoplay>
    <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type='video/mp4' />
    <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type='video/ogg' />
    <source src="http://www.w3schools.com/tags/mov_bbb.webm" type='video/webm' />
  </video>

  <canvas id="myCanvas" width="270" height="135" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>
  <button onclick="savecanvasimage('image.png')">ScreenShot</button>
</body>

</html>

唯一的问题是视频必须在同一台服务器上,并且代码需要在服务器上运行,否则会出错,但它在我的apache服务器上运行良好