html5移动端调用手机摄像头扫描二维码并获取二维码信息代码如下:
[html] view plain copy
<!DOCTYPE html>
<html><head>
<title>HTML5 code Reader</title>
<meta http-equiv="Content-Type" content="text/html charset=gb2312">
</head>
<style type="text/css">
html, body { height: 100% width: 100% text-align:center }
</style>
<script src="jquery-1.9.1.js"></script>
<script>
//这段代 主要是获取摄像头的视频流并显示在Video 签中
var canvas=null,context=null,video=null
window.addEventListener("DOMContentLoaded", function ()
{
try{
canvas = document.getElementById("canvas")
context = canvas.getContext("2d")
video = document.getElementById("video")
var videoObj = { "video": true,audio:false},
flag=true,
MediaErr = function (error)
{
flag=false
if (error.PERMISSION_DENIED)
{
alert('用户拒绝了浏览器请求媒体的权限', '提示')
} else if (error.NOT_SUPPORTED_ERROR) {
alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器', '提示')
} else if (error.MANDATORY_UNSATISFIED_ERROR) {
alert('指定的媒体类型未接收到媒体流', '提示')
} else {
alert('系统未能获取到摄像头,请确保摄像头已正确安装。或尝试刷新页面,重试', '提示')
}
}
//获取媒体的兼容代码,目前只支持(Firefox,Chrome,Opera)
if (navigator.getUserMedia)
{
//qq浏览器不支持
if (navigator.userAgent.indexOf('MQQBrowser') > -1) {
alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器', '提示')
return false
}
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream
video.play()
}, MediaErr)
}
else if(navigator.webkitGetUserMedia)
{
navigator.webkitGetUserMedia(videoObj, function (stream)
{
video.src = window.webkitURL.createObjectURL(stream)
video.play()
}, MediaErr)
}
else if (navigator.mozGetUserMedia)
{
navigator.mozGetUserMedia(videoObj, function (stream) {
video.src = window.URL.createObjectURL(stream)
video.play()
}, MediaErr)
}
else if (navigator.msGetUserMedia)
{
navigator.msGetUserMedia(videoObj, function (stream) {
$(document).scrollTop($(window).height())
video.src = window.URL.createObjectURL(stream)
video.play()
}, MediaErr)
}else{
alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器')
return false
}
if(flag){
alert('为了获得更准确的测试结果,请尽量将二维码置于框中,然后进行拍摄、扫描。 请确保浏览器有权限使用摄像功能')
}
//这个是拍照按钮的事件,
$("#snap").click(function () {startPat()}).show()
}catch(e){
printHtml("浏览器不支持HTML5 CANVAS")
}
}, false)
//打印内容到页面
function printHtml(content){
$(window.document.body).append(content+"<br/>")
}
//开始拍照
function startPat(){
setTimeout(function(){//防止调用过快
if(context)
{
context.drawImage(video, 0, 0, 320, 320)
CatchCode()
}
},200)
}
//抓屏获取图像流,并上传到服务器
function CatchCode() {
if(canvas!=null)
{
//以下开始编 数据
var imgData = canvas.toDataURL()
//将图像转换为base64数据
var base64Data = imgData//.substr(22) //在前端截取22位之后的字符串作为图像数据
//开始异步上
$.post("saveimg.php", { "img": base64Data },function (result)
{
printHtml("解析结果:"+result.data)
if (result.status == "success" && result.data!="")
{
printHtml("解析结果成功!")
}else{
startPat()//如果没有解析出来则重新抓拍解析
}
},"json")
}
}
</script>
<body>
<div id="support"></div>
<div id="contentHolder">
<video id="video" width="320" height="320" autoplay>
</video>
<canvas style="display:none background-color:#F00" id="canvas" width="320" height="320">
</canvas> <br/>
<button id="snap" style="display:none height:50px width:120px">开始扫描</button>
</div>
</body></html>
恰好这几天在尝试,没有兼容所有浏览器。只在手机上试过firefox, 自带浏览器试过不行。以下是代码:---------------------------------------------------------Html----------------------------------------------------------------
<form id="picForm" action="@Url.Action("scan")" method="post">
<input type="hidden" value="" id="code" name="code" />
<input type="hidden" value="" id="status" name="status" />
<section style="position: relative">
<video width="100%" id="video" autoplay="autoplay"></video>
<div id="result" style="position: absolutetop: 0left: 0width:100%height:100%text-align: centerborder:1px solid yellow" onclick="scanCode()">
<section class="smtwo" style="text-align:center">
<h3 ><a class="back" href="${ctx }/index/index.htm">
<img src="images/smtwo_1.png" style="border: none" alt=""></a>请将扫描框对准设备或包装上的二维码 </h3>
</section>
<div id="getCode" style="margin:autowidth:200pxheight:200pxborder:1px solid red"></div>
<canvas width="200" height="200" id="canvas"></canvas>
</div>
</section>
</form
--------------------------------------------------------------Js--------------------------------------------------------------------
<script>
var video, canvas, videoObj
window.addEventListener('DOMContentLoaded', function () {
'use strict'
//调取摄像头
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL
if (navigator.getUserMedia) {
videoObj = { video: true }
video = document.getElementById("video")// $("#video").get(0)
canvas = document.getElementById("canvas")// $("#canvas").get(0)
navigator.getUserMedia({
video: true
}, gotStream, noStream)
} else {
alert('Native web camera streaming (getUserMedia) not supported in this browser.')
}
//调取摄像头成功的回调函数
function gotStream(stream) {
if (video.mozSrcObject !== undefined) {
video.mozSrcObject = stream
} else {
video.src = (window.URL &&window.URL.createObjectURL(stream)) || stream
}
video.play()
//启动摄像头成功之后开始获取二维码
scanCode()
}
//调取摄像头失败的回调函数
function noStream(error) {
alert('An error occurred: [CODE ' + error.code + ']')
}
}, false)
//抓取video画面放入canvas
function photograph() {
var context = canvas.getContext("2d")
// 截取取景框范围(这里用canvas做取景框)
//var x = canvas.clientLeft
//var y = canvas.clientTop
//context.drawImage(video,x, y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height)
var box = getBox()
context.drawImage(video, box.X, box.Y, box.W, box.H, 0, 0, box.W , box.H)
//imageConvertToGray(context)
var imgData = canvas.toDataURL("image/png")
$("#code").val(imgData)
}
function getBox() {
var box = $("#getCode")
var position = { X: $(box).offset().top, Y: $(box).offset().left, W: $(box).width(), H: $(box).height() }
return position
}
//将图片处理成黑白的(二维码扫描需要处理黑白色图片,如果仅用于拍照这一步就省略了)
function imageConvertToGray(ctx) {
var length = canvas.width * canvas.height
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
for (var i = 0i <length * 4i += 4) {
var myRed = imageData.data[i]
var myGreen = imageData.data[i + 1]
var myBlue = imageData.data[i + 2]
myGray = parseInt((myRed + myGreen + myBlue) / 3)
imageData.data[i] = myGray
imageData.data[i + 1] = myGray
imageData.data[i + 2] = myGray
}
ctx.putImageData(imageData, 0, 0)
}
function scanCode() {
//生成图片的base64码
photograph()
var data = { "code": $("#code").val() }
ajaxPostCompliate("@Url.Action("scan")", data, function (result) {
console.info("-----------result--------------" + result)
if (result != null) {//扫描出结果
var obj = JSON.parse(result)
if (obj.org != undefined) {
location.href = "@Url.Action("ScanResult")?org=" + obj.org + "&tp=" + obj.tp + "&ad=" + obj.ad
} else {
alert("该二维码非ME+授权编码")
}
} else {//继续扫描
setTimeout(function () {
scanCode()
}, 2000)
}
})
}
</script>