在移动应用程序中相机到画布

时间:2016-08-19 08:33:21

标签: javascript cordova html5-canvas cordova-plugins

我正在制作将展示live image of back camera on canvas的移动应用。我已经尝试了太多cordova plugin,但在所有系统应用程序中都打开了拍照或录像。

是否有插件或编码方式,所以我可以在back or front camera上看到画布上的现场直播。

感谢。

1 个答案:

答案 0 :(得分:0)

HTML代码

<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>

JS代码

// Put event listeners into place
window.addEventListener("DOMContentLoaded", function () {
    // Grab elements, create settings, etc.
    var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    video = document.getElementById("video"),
    videoObj = { "video": true },
    errBack = function (error) {
        console.log("Video capture error: ", error.code);
    };
    // Put video listeners into place
    if (navigator.getUserMedia) { // Standard
        navigator.getUserMedia(videoObj, function (stream) {
            video.src = stream;
            video.play();
        }, errBack);
    } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
        navigator.webkitGetUserMedia(videoObj, function (stream) {
            video.src = window.webkitURL.createObjectURL(stream);
            video.play();
        }, errBack);
    }
    else if (navigator.mozGetUserMedia) { // Firefox-prefixed
        navigator.mozGetUserMedia(videoObj, function (stream) {
            video.src = window.URL.createObjectURL(stream);
            video.play();
        }, errBack);
    }
}, false);
document.getElementById("snap")
.addEventListener("click", function() {
setInterval(function(){
    context.drawImage(video, 0, 0, 640, 480);
},1);

});

请注意,支持api getUserMedia的浏览器并不意味着它可以呼叫手机上的所有摄像头,它只能调用前置摄像头。