调用navigator.mediaDevices.getUserMedia方法,相机无法对焦

问题描述 投票:0回答:1

我使用 navigator.mediaDevices.getUserMedia 设置相机扫描二维码。当二维码较小时,相机距离太近时无法对焦并捕捉到清晰的图像。设置focusMode不起作用。哪位大佬帮忙看一下?谢谢。下面是我的代码:


<!DOCTYPE html>
<html>

<head>
    <title>HTML5 QR Code Scanner</title>
    <meta charset="utf-8">
    <script src="/assets/js/jsQR.min.js"></script>
</head>

<body>
    <div style="width: 100vw;height: 1200;display: flex;align-items: center;justify-content: center;">
        <video id="video" width="1200" height="1200" autoplay></video>
        <canvas id="canvas" width="1200" height="1200" style="display:none;"></canvas>
    </div>
    <p id="result"></p>
    <script>
        var video = document.getElementById("video");
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        var result = document.getElementById("result");
        let supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
        console.log('supported', supportedConstraints)
        const constraints = {
            width: { min: 640, ideal: 1280 },
            height: { min: 480, ideal: 720 },
            advanced: [{ width: 1920, height: 1280 }, { aspectRatio: 1.333 }, { focusMode: "continuous" }]
        }

        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({
                video: {
                    width: 900, height: 900, 
                    facingMode: { exact: 'environment' },
                    advanced: [{ focusMode: "continuous" }],
                    frameRate: { ideal: 10, max: 15 }
                }
            }).then(function (stream) {
                const track = stream.getVideoTracks()[0];
                track.applyConstraints(constraints).then((e) => {

                }).catch((e => { alert('error') }))
                let constraintsData = track.getConstraints();
                console.log('constraintsData', constraintsData)

                video.srcObject = stream;
                video.play();
                setInterval(function () {
                    context.drawImage(video, 0, 0, 300, 300);
                    var imageData = context.getImageData(0, 0, 300, 300);
                    var code = jsQR(imageData.data, imageData.width, imageData.height);
                    if (code) {
                        alert(code.data)
                    } else {
                        result.textContent = "waitting";
                    }

                }, 500);
            }).catch(function (err) {
                result.textContent = "err:" + err;
            });
        } else {
            result.textContent = "sorry";
        }
    </script>
</body>

</html>

我目前使用过几个第三方JavaScript插件,例如html5-qrcode、qr-scanner、vue-qrcode-reader,也使用过原生API来打开相机。所有对相机进行对焦的尝试都导致无法识别物理对象上较小的二维码

html camera focus
1个回答
0
投票

我在GitHub上搜索了一些HTML扫描项目,发现没有一个能够实现相机对焦。距离近了就变得模糊

© www.soinside.com 2019 - 2024. All rights reserved.