如何使用javascript通过手机上的webbrowser使用livestream扫描条形码?

如何使用javascript通过手机上的webbrowser使用livestream扫描条形码?,javascript,php,android,quaggajs,Javascript,Php,Android,Quaggajs,我正在尝试一种方法来扫描我打印在纸上的irl条形码,以便扫描到我的php网站。只有当我在手机上使用网站时,我才能打开手机摄像头扫描条形码,而他扫描条形码并将其发送给我的代码。代码可以检查我的数据库等 我找到了一个很好的插件来实现这个功能,我一直在玩它,现在我不仅仅是拍照,让它读取条形码并发送到我的代码,但我想让它扫描,同时我把相机放在条形码前面,这样它就会关上相机。这是一个(在桌面上,它需要获得打开网络摄像头的许可) 最后,我想要一个按钮,我在我的网站上点击,打开我的相机,这样我可以扫描代码,当

我正在尝试一种方法来扫描我打印在纸上的irl条形码,以便扫描到我的php网站。只有当我在手机上使用网站时,我才能打开手机摄像头扫描条形码,而他扫描条形码并将其发送给我的代码。代码可以检查我的数据库等

我找到了一个很好的插件来实现这个功能,我一直在玩它,现在我不仅仅是拍照,让它读取条形码并发送到我的代码,但我想让它扫描,同时我把相机放在条形码前面,这样它就会关上相机。这是一个(在桌面上,它需要获得打开网络摄像头的许可)

最后,我想要一个按钮,我在我的网站上点击,打开我的相机,这样我可以扫描代码,当他发现一个条形码,他关闭相机,并向我显示的信息,从产品有这个条形码。有人能帮我吗

下面是我使用和使用的一些代码。(仅适用于拍照)


#interactive.viewport{位置:相对;宽度:100%;高度:自动;溢出:隐藏;文本对齐:中心;}
#interactive.viewport>canvas,#interactive.viewport>video{最大宽度:100%;宽度:100%;}
canvas.drawing,canvas.drawingBuffer{position:absolute;left:0;top:0;}
$(函数(){
//为实时流创建QuaggaJS配置对象
var liveStreamConfig={
输入流:{
键入:“LiveStream”,
限制条件:{
宽度:{min:640},
高度:{min:480},
aspectRatio:{min:1,max:100},
面对模式:前摄像头的“环境”//或“用户”
}
},
定位器:{
补丁大小:“中等”,
半样本:正确
},
numOfWorkers:(navigator.hardwareConcurrency?navigator.hardwareConcurrency:4),
解码器:{
“读者”:[
{“格式”:“代码读取器”,“配置”:{}
]
},
定位:正确
};
//文件API的回退需要不同的inputStream选项。
//其余的都一样
var fileConfig=$.extend(
{}, 
liveStreamConfig,
{
输入流:{
尺码:800
}
}
);
//模式打开时启动实时流扫描程序
$('livestream'u scanner')。on('show.bs.modal',function(e){
Quagga.init(
liveStreamConfig,
功能(err){
如果(错误){
$(“#livestream_scanner.modal body.error').html(“”+err.name+”:“+err.message+”);
嘎嘎。停止();
返回;
}
Quagga.start();
}
);
});
//确保QuaggaJS在可能的范围内画一条线
//实时流上的条形码
Quagga.onProcessed(函数(结果){
var drawingCtx=Quagga.canvas.ctx.overlay,
drawingCanvas=Quagga.canvas.dom.overlay;
如果(结果){
如果(结果框){
clearRect(0,0,parseInt(drawingCanvas.getAttribute(“宽度”)),parseInt(drawingCanvas.getAttribute(“高度”));
result.box.filter(函数(框){
返回框!==result.box;
}).forEach(功能(框){
drawPath(框,{x:0,y:1},drawingCtx,{color:“green”,线宽:2});
});
}
如果(结果框){
drawPath(result.box,{x:0,y:1},drawingCtx,{color:“#00F”,线宽:2});
}
if(result.codesult&&result.codesult.code){
drawPath(result.line,{x:'x',y:'y'},drawingCtx,{color:'red',线宽:3});
}
}
});
//成功读取条形码后,停止quagga并
//一秒钟后关闭模式,让用户注意到
//条形码实际上已经找到了。
Quagga.onDetected(函数(结果){
if(result.codesult.code){
$('#scanner_input').val(result.codesult.code);
嘎嘎。停止();
setTimeout(function(){$('#livestream_scanner').modal('hide');},1000);
}
});
//在任何情况下,当modal关闭时,停止嘎嘎
$('livestream'u scanner')。on('hide.bs.modal',function(){
如果(嘎嘎){
嘎嘎。停止();
}
});
//为在
//文件输入
$(#livestream_扫描器输入:文件”)。关于(“更改”,函数(e){
if(e.target.files&&e.target.files.length){
decodesSingle($.extend({},fileConfig,{src:URL.createObjectURL(e.target.files[0])),函数(result){alert(result.codeResult.code);});
}
});
});
扫描
&时代;
条形码扫描器
使用相机应用程序
接近

致以最诚挚的问候

我花了一些时间亲自完成,但我发现了。我还必须获得证书,这样我的网站才是安全的,并允许我使用
GetUserMedia()这是我现在使用的代码。使用
$code=$\u获取['barcode']我可以用这个变量做其他事情,这一切都取决于你自己

php代码

<button id="opener">Barcode scanner</button>

<div id="modal" title="Barcode scanner">
    <span class="found"></span>
    <div id="interactive" class="viewport"></div>
</div>
条形码扫描仪
Javascript/QuaggaJS

$(function() {
var App = {
        init : function() {
            Quagga.init(this.state, function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                App.attachListeners();
                App.checkCapabilities();
                Quagga.start();
            });
        },
        checkCapabilities: function() {
            var track = Quagga.CameraAccess.getActiveTrack();
            var capabilities = {};
            if (typeof track.getCapabilities === 'function') {
                capabilities = track.getCapabilities();
            }
            this.applySettingsVisibility('zoom', capabilities.zoom);
            this.applySettingsVisibility('torch', capabilities.torch);
        },
        updateOptionsForMediaRange: function(node, range) {
            console.log('updateOptionsForMediaRange', node, range);
            var NUM_STEPS = 6;
            var stepSize = (range.max - range.min) / NUM_STEPS;
            var option;
            var value;
            while (node.firstChild) {
                node.removeChild(node.firstChild);
            }
            for (var i = 0; i <= NUM_STEPS; i++) {
                value = range.min + (stepSize * i);
                option = document.createElement('option');
                option.value = value;
                option.innerHTML = value;
                node.appendChild(option);
            }
        },
        applySettingsVisibility: function(setting, capability) {
            if (typeof capability === 'boolean') {
                var node = document.querySelector('input[name="settings_' + setting + '"]');
                if (node) {
                    node.parentNode.style.display = capability ? 'block' : 'none';
                }
                return;
            }
            if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
                var node = document.querySelector('select[name="settings_' + setting + '"]');
                if (node) {
                    this.updateOptionsForMediaRange(node, capability);
                    node.parentNode.style.display = 'block';
                }
                return;
            }
        },
        initCameraSelection: function(){
            var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();

            return Quagga.CameraAccess.enumerateVideoDevices()
            .then(function(devices) {
                function pruneText(text) {
                    return text.length > 30 ? text.substr(0, 30) : text;
                }
                var $deviceSelection = document.getElementById("deviceSelection");
                while ($deviceSelection.firstChild) {
                    $deviceSelection.removeChild($deviceSelection.firstChild);
                }
                devices.forEach(function(device) {
                    var $option = document.createElement("option");
                    $option.value = device.deviceId || device.id;
                    $option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
                    $option.selected = streamLabel === device.label;
                    $deviceSelection.appendChild($option);
                });
            });
        },
        attachListeners: function() {
            var self = this;

            self.initCameraSelection();
            $(".controls").on("click", "button.stop", function(e) {
                e.preventDefault();
                Quagga.stop();
            });

            $(".controls .reader-config-group").on("change", "input, select", function(e) {
                e.preventDefault();
                var $target = $(e.target),
                    value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
                    name = $target.attr("name"),
                    state = self._convertNameToState(name);

                console.log("Value of "+ state + " changed to " + value);
                self.setState(state, value);
            });
        },
        _accessByPath: function(obj, path, val) {
            var parts = path.split('.'),
                depth = parts.length,
                setter = (typeof val !== "undefined") ? true : false;

            return parts.reduce(function(o, key, i) {
                if (setter && (i + 1) === depth) {
                    if (typeof o[key] === "object" && typeof val === "object") {
                        Object.assign(o[key], val);
                    } else {
                        o[key] = val;
                    }
                }
                return key in o ? o[key] : {};
            }, obj);
        },
        _convertNameToState: function(name) {
            return name.replace("_", ".").split("-").reduce(function(result, value) {
                return result + value.charAt(0).toUpperCase() + value.substring(1);
            });
        },
        detachListeners: function() {
            $(".controls").off("click", "button.stop");
            $(".controls .reader-config-group").off("change", "input, select");
        },
        applySetting: function(setting, value) {
            var track = Quagga.CameraAccess.getActiveTrack();
            if (track && typeof track.getCapabilities === 'function') {
                switch (setting) {
                case 'zoom':
                    return track.applyConstraints({advanced: [{zoom: parseFloat(value)}]});
                case 'torch':
                    return track.applyConstraints({advanced: [{torch: !!value}]});
                }
            }
        },
        setState: function(path, value) {
            var self = this;

            if (typeof self._accessByPath(self.inputMapper, path) === "function") {
                value = self._accessByPath(self.inputMapper, path)(value);
            }

            if (path.startsWith('settings.')) {
                var setting = path.substring(9);
                return self.applySetting(setting, value);
            }
            self._accessByPath(self.state, path, value);

            console.log(JSON.stringify(self.state));
            App.detachListeners();
            Quagga.stop();
            App.init();
        },
        inputMapper: {
            inputStream: {
                constraints: function(value){
                    if (/^(\d+)x(\d+)$/.test(value)) {
                        var values = value.split('x');
                        return {
                            width: {min: parseInt(values[0])},
                            height: {min: parseInt(values[1])}
                        };
                    }
                    return {
                        deviceId: value
                    };
                }
            },
            numOfWorkers: function(value) {
                return parseInt(value);
            },
            decoder: {
                readers: function(value) {
                    if (value === 'ean_extended') {
                        return [{
                            format: "ean_reader",
                            config: {
                                supplements: [
                                    'ean_5_reader', 'ean_2_reader'
                                ]
                            }
                        }];
                    }
                    return [{
                        format: value + "_reader",
                        config: {}
                    }];
                }
            }
        },
        state: {
            inputStream: {
                type : "LiveStream",
                constraints: {
                    width: {min: 640},
                    height: {min: 480},
                    aspectRatio: {min: 1, max: 100},
                    facingMode: "environment" // or user
                }
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            numOfWorkers: 2,
            frequency: 10,
            decoder: {
                readers : [{
                    format: "code_128_reader",
                    config: {}
                }]
            },
            locate: true
        },
        lastResult : null
    };

    App.init();



    Quagga.onDetected(function(result) {
        var code = result.codeResult.code;
        Quagga.stop();
        window.location.href="scannerview.php?barcode=" + code;
    });
});
$(函数(){
变量应用={
init:function(){
$(function() {
var App = {
        init : function() {
            Quagga.init(this.state, function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                App.attachListeners();
                App.checkCapabilities();
                Quagga.start();
            });
        },
        checkCapabilities: function() {
            var track = Quagga.CameraAccess.getActiveTrack();
            var capabilities = {};
            if (typeof track.getCapabilities === 'function') {
                capabilities = track.getCapabilities();
            }
            this.applySettingsVisibility('zoom', capabilities.zoom);
            this.applySettingsVisibility('torch', capabilities.torch);
        },
        updateOptionsForMediaRange: function(node, range) {
            console.log('updateOptionsForMediaRange', node, range);
            var NUM_STEPS = 6;
            var stepSize = (range.max - range.min) / NUM_STEPS;
            var option;
            var value;
            while (node.firstChild) {
                node.removeChild(node.firstChild);
            }
            for (var i = 0; i <= NUM_STEPS; i++) {
                value = range.min + (stepSize * i);
                option = document.createElement('option');
                option.value = value;
                option.innerHTML = value;
                node.appendChild(option);
            }
        },
        applySettingsVisibility: function(setting, capability) {
            if (typeof capability === 'boolean') {
                var node = document.querySelector('input[name="settings_' + setting + '"]');
                if (node) {
                    node.parentNode.style.display = capability ? 'block' : 'none';
                }
                return;
            }
            if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
                var node = document.querySelector('select[name="settings_' + setting + '"]');
                if (node) {
                    this.updateOptionsForMediaRange(node, capability);
                    node.parentNode.style.display = 'block';
                }
                return;
            }
        },
        initCameraSelection: function(){
            var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();

            return Quagga.CameraAccess.enumerateVideoDevices()
            .then(function(devices) {
                function pruneText(text) {
                    return text.length > 30 ? text.substr(0, 30) : text;
                }
                var $deviceSelection = document.getElementById("deviceSelection");
                while ($deviceSelection.firstChild) {
                    $deviceSelection.removeChild($deviceSelection.firstChild);
                }
                devices.forEach(function(device) {
                    var $option = document.createElement("option");
                    $option.value = device.deviceId || device.id;
                    $option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
                    $option.selected = streamLabel === device.label;
                    $deviceSelection.appendChild($option);
                });
            });
        },
        attachListeners: function() {
            var self = this;

            self.initCameraSelection();
            $(".controls").on("click", "button.stop", function(e) {
                e.preventDefault();
                Quagga.stop();
            });

            $(".controls .reader-config-group").on("change", "input, select", function(e) {
                e.preventDefault();
                var $target = $(e.target),
                    value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
                    name = $target.attr("name"),
                    state = self._convertNameToState(name);

                console.log("Value of "+ state + " changed to " + value);
                self.setState(state, value);
            });
        },
        _accessByPath: function(obj, path, val) {
            var parts = path.split('.'),
                depth = parts.length,
                setter = (typeof val !== "undefined") ? true : false;

            return parts.reduce(function(o, key, i) {
                if (setter && (i + 1) === depth) {
                    if (typeof o[key] === "object" && typeof val === "object") {
                        Object.assign(o[key], val);
                    } else {
                        o[key] = val;
                    }
                }
                return key in o ? o[key] : {};
            }, obj);
        },
        _convertNameToState: function(name) {
            return name.replace("_", ".").split("-").reduce(function(result, value) {
                return result + value.charAt(0).toUpperCase() + value.substring(1);
            });
        },
        detachListeners: function() {
            $(".controls").off("click", "button.stop");
            $(".controls .reader-config-group").off("change", "input, select");
        },
        applySetting: function(setting, value) {
            var track = Quagga.CameraAccess.getActiveTrack();
            if (track && typeof track.getCapabilities === 'function') {
                switch (setting) {
                case 'zoom':
                    return track.applyConstraints({advanced: [{zoom: parseFloat(value)}]});
                case 'torch':
                    return track.applyConstraints({advanced: [{torch: !!value}]});
                }
            }
        },
        setState: function(path, value) {
            var self = this;

            if (typeof self._accessByPath(self.inputMapper, path) === "function") {
                value = self._accessByPath(self.inputMapper, path)(value);
            }

            if (path.startsWith('settings.')) {
                var setting = path.substring(9);
                return self.applySetting(setting, value);
            }
            self._accessByPath(self.state, path, value);

            console.log(JSON.stringify(self.state));
            App.detachListeners();
            Quagga.stop();
            App.init();
        },
        inputMapper: {
            inputStream: {
                constraints: function(value){
                    if (/^(\d+)x(\d+)$/.test(value)) {
                        var values = value.split('x');
                        return {
                            width: {min: parseInt(values[0])},
                            height: {min: parseInt(values[1])}
                        };
                    }
                    return {
                        deviceId: value
                    };
                }
            },
            numOfWorkers: function(value) {
                return parseInt(value);
            },
            decoder: {
                readers: function(value) {
                    if (value === 'ean_extended') {
                        return [{
                            format: "ean_reader",
                            config: {
                                supplements: [
                                    'ean_5_reader', 'ean_2_reader'
                                ]
                            }
                        }];
                    }
                    return [{
                        format: value + "_reader",
                        config: {}
                    }];
                }
            }
        },
        state: {
            inputStream: {
                type : "LiveStream",
                constraints: {
                    width: {min: 640},
                    height: {min: 480},
                    aspectRatio: {min: 1, max: 100},
                    facingMode: "environment" // or user
                }
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            numOfWorkers: 2,
            frequency: 10,
            decoder: {
                readers : [{
                    format: "code_128_reader",
                    config: {}
                }]
            },
            locate: true
        },
        lastResult : null
    };

    App.init();



    Quagga.onDetected(function(result) {
        var code = result.codeResult.code;
        Quagga.stop();
        window.location.href="scannerview.php?barcode=" + code;
    });
});