首页 > 解决方案 > 如何创建视频和画布然后将其绘制到画布上?

问题描述

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

<!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>

标签: javascriptcanvas

解决方案


您不需要画布即可在 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>


推荐阅读