How to change canvas size that fits video sizes dynamically

Hi,

I got 2 videos and 1 canvas. Let’s say:


canvas = document.querySelector("canvas");
video_1 = document.getElementById("video_1");
video_2 = document.getElementById("video_2");

The canvas size resizes perfectly dynamically with theses separate code:


video_1.onplay = function() {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            draw();
};
function draw() {
            if(video_1.paused || video_1.ended) return false;
            ctx.drawImage(video_1, 0, 0);
            setTimeout(draw, 20);
}
.
.
video_2.onplay = function() {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            draw();
};
function draw() {
            if(video_2.paused || video_2.ended) return false;
            ctx.drawImage(video_2, 0, 0);
            setTimeout(draw, 20);
}

The codes above do not response to video element clicked so I added:


switch(clicked.id) {
            case ''video_1":
	    videoElement = "video_1"';
	    break;
            case ''video_2":
	    videoElement = "video_2";
	    break;
}

So it looks like this:


switch(clicked.id) {
            case ''video_1":
	    videoElement = "video_1"';
	    break;
            case ''video_2":
	    videoElement = "video_2";
	    break;
}
videoElement.onplay = function() {
            canvas.width = videoElement.videoWidth;
            canvas.height = videoElement.videoHeight;
            draw();
};
function draw() {
            if(videoElement.paused || videoElement.ended) return false;
            ctx.drawImage(videoElement, 0, 0);
            setTimeout(draw, 20);
}

The canvas size is re-sized but it appeared to be something like 300px X 180px for both elements clicked. I don’t know where this number comes from. When I try to assign a fixed size such as 640px X 360px, the clicked video appeared to be very large and the canvas display only part of it.

How do I get the canvas size changed dynamically according to the playing video size.

Hope I explain my problem clearly.

Thanks,
Ket

Never mind I found a solution and it works on Firefox too.