将视频标记放在Canvas标记上

时间:2015-02-14 07:20:34

标签: html5 canvas html5-canvas html5-video

我想将视频播放器放在Canvas上。

(因为我的视频是alpha通道,我想在jpg上播放视频)

我在下面制作了如下代码 HTML

<video id="mainVideo" src="item0.mp4">
</video>
<canvas id="mainCanvas">
</canvas>

我的css

#mainCanvas {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 400;
    height: 400;
}

#mainVideo {
    position: absolute;
    top: 300;
    left: 300;
    margin: -50px 0 0 -50px;
}

我的javascript

document.addEventListener('DOMContentLoaded', function(){
    var canvas = document.getElementById('mainCanvas');
    var context = canvas.getContext('2d');
    var img = new Image();
    img.src = "image.jpg";
    context.drawImage(img, 0,0)
},false);

在我的想法中,它显示了jpg和视频。

Howevere,只有jpg出现在它上面(视频可能被画布隐藏了?)

请让我知道如何在jpg上支付视频?

我的想法(一起使用HTML和画布)是否正确?

1 个答案:

答案 0 :(得分:1)

您可以在html画布上绘制图像和视频。

画布可以使用图像对象或视频元素作为其图像源。

两者都是使用单独的context.drawImage命令

绘制的

以下是示例代码:

// reference to canvas and context
var canvas=document.getElementById("mainCanvas");
var context=canvas.getContext("2d");
var cw,ch;

// reference to video element
var v = document.getElementById('mainVideo');

// wait until video metadata is loaded
v.addEventListener( "loadedmetadata", function(e){

    // set the canvas size to the video size
    cw=canvas.width=v.videoWidth;
    ch=canvas.height=v.videoHeight;

    // listen for when user presses play
    v.addEventListener('play', function(){
        // start loop that displays video frames on canvas
        requestAnimationFrame(animate);
    },false);


}, false );   

// loop that displays video frames on canvas
function animate(time){

    // stop the loop if user stops video
    if(v.paused || v.ended){ return; }

    // draw the 1 current video frame on the canvas
    context.drawImage(v,0,0,cw,ch);

    // also draw your image on the canvas
    context.drawImage(img,0,0);

    // request another loop 
    requestAnimationFrame(animate);

}