2

我有一个页面,它使用 HTML5 getUserMedia 功能从用户的网络摄像头捕获图像。将捕获的图像渲染到画布时,我在缩放时遇到严重的不一致。实际只渲染图像的顶角,就好像它不是捕获视频元素,而是从底层流中切片。奇怪的是,当我使用这种技术访问大多数其他网站时,我没有这个问题。我在 Windows 7 上运行 Chrome 29.0.1547.76 m,在 2011 MacBook Pro 上运行。

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            var openCameraButton;
            var takePictureButton;
            var mediaStream;
            var video;
            var canvas;
            var context;

            navigator.getMedia = ( navigator.getUserMedia ||
                navigator.webkitGetUserMedia ||
                navigator.mozGetUserMedia ||
                navigator.msGetUserMedia);

            function onLoad(){
                video = document.querySelector('video');
                canvas = document.querySelector('canvas');
                context = canvas.getContext('2d');
                context.imageSmoothingEnabled = true;
                context.webkitImageSmoothingEnabled = true;
                context.mozImageSmoothingEnabled = true;
            };

            function openCamera(){
                navigator.getMedia(
                    { video:true, audio: false },
                    function(localMediaStream){
                        mediaStream = localMediaStream;
                        video.src=window.URL.createObjectURL(localMediaStream);
                    },
                    function(err){
                        alert('Unable to support live capture.');
                    }
                );
            }

            function takePicture(){
                var w = video.videoWidth;
                var h = video.videoHeight;

                context.drawImage(video,0,0,w,h);

                canvas.style.display='block';
                video.style.display='none';
            }
        </script>
    </head>
    <body onload="onLoad();">
        <div>
            <video autoplay style="width:640px; height:480px;"></video>
            <canvas style="width:640px; height:480px; display:none;"></canvas>
        </div>
        <div>
            <button id="openCameraButton" type="button" onclick="openCamera();" >Open Camera</button>
            <button id="takePictureButton"  type="button" onclick="takePicture();" >Take Picture</button>
        </div>
    </body>
</html>

有任何想法吗?

4

1 回答 1

3

请试试这个:

function takePicture(){
    var w = video.videoWidth;
    var h = video.videoHeight;
    canvas.width = w;
    canvas.height = h;
    context.drawImage(video,0,0,w,h);
    canvas.style.display='block';
    video.style.display='none';
}
于 2013-10-04T19:10:10.007 回答