HTML5画布drawImage剪辑大小不正确的图像

时间:2018-03-24 11:42:15

标签: javascript html5 html5-canvas

我一直在尝试使用HTML5画布drawImage从视频中获取静态海报,但如下所示的javascript代码仅捕获部分框架,我似乎不知道为什么?这是代码:

<html>
<body>
<video muted="" id="video" preload="auto" loop="" 
autoplay="auto" src="https://funpd.com/uploads/14094-when-your-crush-stares-at-you.mp4" type="video/mp4"></video>
<button onclick="capture();">Capture</button> <br/>
<canvas id="canvas"></canvas>
<script>
function capture(){
    var canvas = document.getElementById('canvas');
    var video = document.getElementById('video');
    canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
}
</script>
</body>
</html>

您可以访问https://funpd.com/test以供参考。我想要捕获整个视频帧,上面的代码只捕获帧的一部分。

2 个答案:

答案 0 :(得分:1)

您必须事先相应地设置画布的widthheight

canvas.width = video.videoWidth;
...

答案 1 :(得分:0)

默认canvas尺寸为300x150像素(https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) 您可以调整画布大小以适应视频(如其他答案中所示),也可以使用&#34; long&#34; drawImage的变体,您也可以在其中指定目标矩形,从而调整视频大小以适合您的画布。

为了保持宽高比正确,并且可能将图像置于画布的中心位置,可以应用一些数学运算:

&#13;
&#13;
function capture(){
  var canvas = document.getElementById('canvas');
  var video = document.getElementById('video');
  var cw=canvas.width;
  var ch=canvas.height;
  var vw=video.videoWidth;
  var vh=video.videoHeight;
  if(cw/ch<vw/vh){
    var th=cw*vh/vw;
    canvas.getContext('2d').drawImage(video, 0, 0, vw, vh, 0, (ch-th)/2, cw, th);
  }else{
    var tw=ch*vw/vh;
    canvas.getContext('2d').drawImage(video, 0, 0, vw, vh, (cw-tw)/2, 0, tw, ch);
  }
}
&#13;
<video muted="" id="video" preload="auto" loop="" 
autoplay="auto" src="https://funpd.com/uploads/14094-when-your-crush-stares-at-you.mp4" type="video/mp4"></video>
<button onclick="capture();">Capture</button> <br/>
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;