0

I would like to put the video player on Canvas.

(Since my video is alpha channel and I would like to play the video on jpg)

I made code like this below html

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

my 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;
}

my 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);

In my thought,it shows the jpg and video on it.

Howevere, only the jpg appears on it,(video might be concealed by canvas??)

please let me know how can I pay the video on jpg??

My idea (using HTML and canvas together)is correct?

whitebear
  • 11,200
  • 24
  • 114
  • 237

1 Answers1

1

You can draw both images and video on html canvas.

The canvas can use either image objects or video elements as its image source.

Both are drawn using separate context.drawImage commands

Here's example code:

// 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);

}
markE
  • 102,905
  • 11
  • 164
  • 176
  • Thanks!! it is great answer for me. I understood I need to refresh image each frames by this animate function. – whitebear Feb 14 '15 at 08:13