Home >Web Front-end >H5 Tutorial >Using HTML5 to take pictures sample code_html5 tutorial tips

Using HTML5 to take pictures sample code_html5 tutorial tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 15:49:011550browse

Demo address: HTML5 photo taking demo
First, let’s take a look at the HTML code structure. Of course, this part of the DOM content should be dynamically loaded and generated after the user allows the use of their camera event.
Note: We use the resolution of 640X480. If you use JS to dynamically generate it, you can flexibly control the resolution.

Copy code
The code is as follows:





< ;canvas id="canvas" width="640" height="480">

JavaScript
As long as the above HTML element is created, the JavaScript part will be simple It’s easier than you think:

Copy the code
The code is as follows:

/ / Set event listening, DOM content loading is completed, and the effect is similar to jQuery's $.ready().
window.addEventListener("DOMContentLoaded", function() {
// The canvas element will be used for capturing
var canvas = document.getElementById("canvas"),
context = canvas.getContext( "2d"),
// video element, which will be used to receive and play the camera's data stream
video = document.getElementById("video"),
videoObj = { "video": true },
// An error callback function, prints error information on the console
errBack = function(error) {
if("object" === typeof window.console){
console.log ("Video capture error: ", error.code);
}
};
// Put video listeners into place
// For standard browsers
if(navigator.getUserMedia ) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play() ;
}, errBack);
}
// Event monitoring for the photo button
document.getElementById("snap").addEventListener("click", function() {
/ / Draw to the canvas
context.drawImage(video, 0, 0, 640, 480);
});
}, false);

Finally, remember to say Put your web page under the web server and access it through the http protocol.
In addition, the browser version needs to be newer and support the new features of HTML5.
The translator is not qualified because he did not translate according to the original text. The browser used is chrome 28.
Finally, paste the complete code, which is rather dull.

Copy code
The code is as follows:



브라우저 <br><meta name=" " content="EditPlus"> <br><meta name="Author" content="renfufei@qq.com"> <br><meta name="Description" content="투자자: http: / /davidwalsh.name/browser-camera"> <br><script> <br>// 이벤트 수신을 설정하고 DOM 콘텐츠가 로드되며 효과는 jQuery의 $.ready()와 유사합니다. <br>window.addEventListener("DOMContentLoaded", function() { <br>// 캔버스 요소는 캡처에 사용됩니다. <br>var canvas = document.getElementById("canvas"), <br>context = canvas. getContext( "2d"), <br>// 카메라의 데이터 스트림을 수신하고 재생하는 데 사용되는 video 요소 <br>video = document.getElementById("video"), <br>videoObj = { "video" : true }, <br>// 오류 콜백 함수, 콘솔에 오류 정보를 인쇄합니다. <br>errBack = function(error) { <br>if("object" === typeof window.console){ <br> console.log("비디오 캡처 오류: ", error.code); <br>} <br>}// 비디오 리스너를 제자리에 배치 <br>// 표준 브라우저의 경우<br>if(navigator. getUserMedia ) { // 표준 <br>navigator.getUserMedia(videoObj, function(stream) { <br>video.src = stream; <br>video.play(); <br>}, errBack); else if(navigator.webkitGetUserMedia) { // WebKit 접두어 <br>navigator.webkitGetUserMedia(videoObj, function(stream){ <br>video.src = window.webkitURL.createObjectURL(stream); <br>video.play( ) ; <br>}, errBack); <br>} <br>// 사진 버튼에 대한 이벤트 모니터링<br>document.getElementById("snap").addEventListener("click", function() { <br> / / 캔버스에 그리기 <br>context.drawImage(video, 0, 0, 640, 480) <br>}, false); /head> <br><body> <br><div> <br><!-- <br />설명: 이 div는 웹캠, 웹캠 <br />사용을 허용한 후 동적으로 생성되어야 합니다. : 640 *480, 물론 동적으로 제어할 수 있습니다! <br />--> <br /><!-- <br />이상적으로 이러한 요소는 <br />클라이언트가 비디오를 지원하는지 확인될 때까지 생성되지 않습니다. /camera, 그러나 <br />관련 요소를 설명하기 위해 마크업(JavaScript 아님)으로 생성되었습니다. <br />--><video id="video" width="640" height= "480" 자동 재생></video> <br><button id="snap">스냅 사진</button><br><canvas id="canvas" width="640" height="480" ></캔버스> <br></body> <br><br> </div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="HTML5 maze game (collision detection) example 1_html5 tutorial skills" href="https://m.php.cn/faq/6229.html">HTML5 maze game (collision detection) example 1_html5 tutorial skills</a></span><span>Next article:<a class="dBlack" title="HTML5 maze game (collision detection) example 1_html5 tutorial skills" href="https://m.php.cn/faq/6233.html">HTML5 maze game (collision detection) example 1_html5 tutorial skills</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/348281.html" title="AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds" class="aBlack">AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348372.html" title="HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)" class="aBlack">HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348373.html" title="Detailed explanation of image drawing examples in HTML5 canvas 9" class="aBlack">Detailed explanation of image drawing examples in HTML5 canvas 9</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348374.html" title="Regular expressions and new HTML5 elements" class="aBlack">Regular expressions and new HTML5 elements</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348469.html" title="How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server" class="aBlack">How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body><!-- Matomo --><script> var _paq = window._paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://tongji.php.cn/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '9']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script><!-- End Matomo Code --></html>