如何使用HTML5实现拍照上传应用 · Web前端
2个回答
展开全部
这是例子,拿走
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>camera</title>
<script language="javascript" src="jquery.js"></script>
</head>
<body>
<div id="contentHolder">
<video id="video" width="320" height="320" autoplay></video>
<button id="snap" style="display:block" onClick="getcamera()">拍照</button>
<canvas style="display:block" id="canvas" width="320" height="320"></canvas>
</div>
<div id="support"></div>
<div id="mydatetime"></div>
<script language="javascript">
//判断浏览器是否支持HTML5 Canvas
$(document).ready(function(){
try {
//动态创建一个canvas元 ,并获取他2Dcontext。如果出现异常则表示不支持 document.createElement("canvas").getContext("2d");
document.getElementById("support").innerHTML = "浏览器支持HTML5 CANVAS";
}
catch (e) {
document.getElementById("support").innerHTML = "浏览器不支持HTML5 CANVAS";
}
document.getElementById("mydatetime").innerHTML=getNowFormatDate();
});
function getcamera(){
//这段代 主要是获取摄像头的视频流并显示在Video 签中
window.addEventListener("DOMContentLoaded", function () {
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);
};
//navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow
if (navigator.getUserMedia) {
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream;
video.play();
}, errBack);
}
else if(navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
//这个是拍照按钮的事件
$("#snap").click(function () {
context.drawImage(video, 0, 0, 320, 320);
});
}, false);
}
//定时器
//var interval = setInterval(CatchCode, "300"); //这个是 刷新上 图像的
function CatchCode() {
$("#snap").click();
//实际运用可不写,测试代 , 为单击拍照按钮就获取了当前图像,有其他用途
var canvans = document.getElementById("canvas");
//获取浏览器页面的画布对象
}
/*
//以下开始编 数据
var imgData = canvans.toDataURL();
//将图像转换为base64数据
var base64Data = imgData.substr(22);
//在前端截取22位之后的字符串作为图像数据
//开始异步上
$.post("uploadImgCode.ashx", { "img": base64Data }, function (data, status) {
if (status == "success") {
if (data == "OK") {
alert("二维 已经解析");
}
else {
// alert(data);
}
}
else {
alert("数据上 失败");
}
}, "text");
*/
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
</script>
</body>
</html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |