繁体   English   中英

如何创建视频和画布然后将其绘制到画布上?

[英]How to create a video and a canvas then draw it to the canvas?

我无法将此视频元素添加到它在画布内创建的画布中,但不会绘制到画布上。 谁能向我解释一下我哪里出错了?

<!DOCTYPE html>
<html>
<style>
canvas {
  border: 1px solid black;
}
</style>
<body>

<div id="popUpCanvas">

</div>

<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  var videoCanvas = document.createElement("Canvas");
  var video = document.createElement("Video");
  var source = document.createElement("Source");
  var context = videoCanvas.getContext('2d');

    videoCanvas.setAttribute('class', 'CanvasVideo');
    videoCanvas.setAttribute('id', 'CanvasVideo');

    video.setAttribute('class', 'videoCanvas');
    video.setAttribute('id', 'videoCanvas');
    video.setAttribute('controls', '');
    video.setAttribute('autoplay', '');

    source.setAttribute('class', 'videoSource');
    source.setAttribute('id', 'videoSource');
    source.setAttribute('src', 'http://www.imgur.com/mClEpxu.mp4');
    source.setAttribute('type', 'video/mp4');

  video.appendChild(source);
  videoCanvas.appendChild(video);

    context.drawImage(video,0,0,100,100);

  document.getElementById("popUpCanvas").appendChild(videoCanvas);
}
</script>

</body>
</html>

您需要在每一帧更新画布,以便实时显示视频内容。 这可以通过动画帧来实现:

requestAnimationFrame(updateVideo);
function updateVideo() {
    if (!video.ended) requestAnimationFrame(updateVideo);
    context.clearRect(0,0,100,100);
    context.drawImage(video,0,0,100,100); 
}

此函数将在每一帧之前调用,以便它更新屏幕上的视频。 希望这可以帮助。

您不需要画布来在 HTML5 上显示视频,这是工作代码的示例:

视频周围会有画布边框,但不需要使用canvas元素。

 <!DOCTYPE html> <html> <style> .CanvasVideo { border: 1px solid black; width: 300px; height: 300px; } video { height: inherit; width: inherit; } </style> <body> <div id="popUpCanvas"> </div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var videoCanvas = document.createElement("Div"); var video = document.createElement("Video"); var source = document.createElement("Source"); videoCanvas.setAttribute('class', 'CanvasVideo'); videoCanvas.setAttribute('id', 'CanvasVideo'); video.setAttribute('class', 'videoCanvas'); video.setAttribute('id', 'videoCanvas'); video.setAttribute('controls', ''); video.setAttribute('autoplay', ''); source.setAttribute('class', 'videoSource'); source.setAttribute('id', 'videoSource'); source.setAttribute('src', 'http://www.imgur.com/mClEpxu.mp4'); source.setAttribute('type', 'video/mp4'); video.appendChild(source); videoCanvas.appendChild(video); document.getElementById("popUpCanvas").appendChild(videoCanvas); } </script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM