Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 video frame capture to bitmap

I got this script:

function capture(video, scaleFactor) {
    if(scaleFactor == null){
        scaleFactor = 1;
    }
    var w = video.videoWidth * scaleFactor;
    var h = video.videoHeight * scaleFactor;
    var canvas = document.createElement('canvas');
    canvas.width  = w;
    canvas.height = h;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, w, h);


    return canvas;
} 


function shoot(){
    var video  = document.getElementById(videoId);
    var output = document.getElementById('output');
    var canvas = capture(video, scaleFactor);
    canvas.onclick = function(){
        window.open(this.toDataURL());
    };
    snapshots.unshift(canvas);
    output.innerHTML = '';
    for(var i=0; i<1; i++){
        output.appendChild(snapshots[i]);
    }

}

What I want to do is export the snapshot to a bitmap image. I read that I could use this line:

canvas.toDataURL('image/jpeg');

But I don't know where to add it.

Any ideas?

like image 665
Alejandro Ar Avatar asked Nov 14 '11 21:11

Alejandro Ar


2 Answers

ctx.drawImage(video, 0, 0, w, h); canvas.toDataURL(...)

toDataURL will return you a string which is usually base64 encoded image (file) content. You can display it in image tag by < img src="the string"/>. Or you can use javascript to do whatever you want...

like image 170
Tom Fishman Avatar answered Oct 23 '22 15:10

Tom Fishman


Pass it to window.open

canvas.onclick = function () {
    window.open(canvas.toDataURL('image/png'));
};

Full Example : http://www.nihilogic.dk/labs/canvas2image/

like image 35
pradeek Avatar answered Oct 23 '22 17:10

pradeek