簡體   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