use*_*449 6 javascript html5 canvas
我正试图在画布上画一个视频.为了实现这一点,我在Javascript中捕获onMouseDown和onMouseUp事件以获取每个事件的x和y坐标(我需要在画布内设置视频的位置,宽度和高度).
因此,每次我在画布上绘制视频时,我应该停止之前的创建,并且必须播放新的视频.两个问题:
1)视频不播放(该功能仅绘制第一帧),但他的音频确实如此
2)我怎样才能让之前绘制的视频停止?
演示:http://jsfiddle.net/e3c3kore/
<body>
<canvas id="canvas" width="800" height="600"></canvas>
</body>
var canvas, context, xStart, yStart, xEnd, yEnd;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mouseup", mouseUp);
function mouseDown(e) {
xStart = e.offsetX;
yStart = e.offsetY;
}
function mouseUp(e) {
xEnd = e.offsetX;
yEnd = e.offsetY;
if (xStart != xEnd && yStart != yEnd) {
var video = document.createElement("video");
video.src = "http://techslides.com/demos/sample-videos/small.mp4";
video.addEventListener('loadeddata', function() {
video.play();
context.drawImage(video, xStart, yStart, xEnd-xStart, yEnd-yStart);
});
}
}
Run Code Online (Sandbox Code Playgroud)
Bli*_*n67 11
您需要设置连续渲染。您仅渲染视频的第一帧。Canvas 很笨,不知道视频。您刚刚将视频中的像素转储到画布上。您需要不断更新画布。
最好的方法是使用requestAnimationFrame它来确保所有内容都与浏览器自己的渲染同步。
在下面的示例中,渲染在视频加载时开始。如果您加载第二个视频,请务必结束之前的更新。
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var video = document.createElement("video");
video.src = "http://techslides.com/demos/sample-videos/small.mp4";
video.addEventListener('loadeddata', function() {
video.play(); // start playing
update(); //Start rendering
});
function update(){
ctx.drawImage(video,0,0,256,256);
requestAnimationFrame(update); // wait for the browser to be ready to present another animation fram.
}Run Code Online (Sandbox Code Playgroud)
#canV {
width:256px;
height:256px;
}Run Code Online (Sandbox Code Playgroud)
<canvas id="canV" width=256 height=256></canvas>Run Code Online (Sandbox Code Playgroud)
小智 6
1) drawImage() 方法只被调用一次。它需要每帧调用一次。
2) 调用 pause() 方法停止视频。
例如,以下代码在鼠标向上时启动一个计时器循环(用于绘制帧),并在鼠标向下时停止任何先前的视频。
var canvas, context, video, xStart, yStart, xEnd, yEnd;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mouseup", mouseUp);
function mouseDown(e) {
if (video) {
video.pause();
video = null;
context.clearRect(0, 0, canvas.width, canvas.height);
}
xStart = e.offsetX;
yStart = e.offsetY;
}
function mouseUp(e) {
xEnd = e.offsetX;
yEnd = e.offsetY;
if (xStart != xEnd && yStart != yEnd) {
video = document.createElement("video");
video.src = "http://techslides.com/demos/sample-videos/small.mp4";
video.addEventListener('loadeddata', function() {
console.log("loadeddata");
video.play();
setTimeout(videoLoop, 1000 / 30);
});
}
}
function videoLoop() {
if (video && !video.paused && !video.ended) {
context.drawImage(video, xStart, yStart, xEnd - xStart, yEnd - yStart);
setTimeout(videoLoop, 1000 / 30);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12014 次 |
| 最近记录: |