javascript - 如何创建视频和画布然后将其绘制到画布上?
问题描述
我无法将此视频元素添加到它在画布内创建但不会绘制到画布的画布中。谁能向我解释我哪里出错了?
<!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>
解决方案
您不需要画布即可在 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>
推荐阅读
- c# - 使用 ModelState 验证 DTO
- java - 在 Netty 服务器中未调用 RequestHandler
- gtk3 - 如何使用 GTK 将按键事件发送到非活动条目
- json - 在 Python 3 中从 Google API JSON 中提取几何/位置键:AttributeError: 'list' object has no attribute 'read'
- python - 如何在python中解析requests.session cookie属性
- pandas - 如何按日期列的月和日部分分组,以便一年获得 365 个组
- react-native - 如何在标题中有自定义导航
- apache-camel - concurrentConsumers 值是否会影响 Camel 处理器线程的数量?
- java - 碰到边框时如何更改对象的大小?
- javascript - 在 PHP 中通过表单发送 base64 图像时 $_POST 为空