基于Html5的网页大头贴

时间:2021-09-25 13:26:50

Html5技术越来越侵蚀着这个互联网,不得不承认,Html5所带来的改变还是很大的,一次偶然的机会,找到了Html5调用电脑摄像头的API,于是想到了做一个网页版大头贴来实现拍照与简单修改的功能,初期的版本还比较简单,大家可以看一下效果。saymagic.sinaapp.com/takephoto/。(注意,要用Chrome浏览器!!!)

好的,那接下来我就将介绍下这个的实现过程,代码已在GitHub上开源,后面会给出下载地址,先声明一下,该网站运行在sae平台上,所以图片的上传与存储在用sae的storage,所以下载下来若不是在sae上部署,就会有一些功能用不了,即使用sae的话也需要自己新建storage等,所以copy党们注意一下。

这个的代码量还是不少的,首先,看一下主界面的代码吧,

<!DOCTYPE html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6 lt8"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7 lt8"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8 lt8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="UTF-8" />
        <!-- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">  -->
        <title>Login and Registration Form with HTML5 and CSS3 Demo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
        <meta name="description" content="Login and Registration Form with HTML5 and CSS3" />
        <meta name="keywords" content="html5, css3, form, switch, animation, :target, pseudo-class" />
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/style2.css" />
		<link rel="stylesheet" type="text/css" href="css/animate-custom.css" />
		<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
		<script type="text/javascript" src="js/jquery.popImage.mini.js"></script>	
		<link href="index.css" rel="stylesheet" type="text/css">
		<script language="javascript">
window.addEventListener("DOMContentLoaded", function() {
	var timer;
	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); 
		};
	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);
	}
	document.getElementById("snap").addEventListener("click", function() {
		clearTimeout(timer);
		video.pause();
	});
	document.getElementById("rephotograph").addEventListener("click", function() {
		clearTimeout(timer);
		video.play();
	});
	document.getElementById("autophotograph").addEventListener("click",function(){
		video.play();
		timer = setTimeout(function(){	
			video.pause();
		},3000);
	});
	document.getElementById("change").addEventListener("click", function() {
		context.drawImage(video, 0, 0, 440, 330);
	});

    var saveFile = function(data, filename) {
        var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
        save_link.href = data;
        save_link.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);
    };
	document.getElementById("download").addEventListener("click", function() {
        var myCanvas = document.getElementById("canvas");  

        var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");   
        var filename = 'paint_' + (new Date()).getTime() + '.png';
        saveFile(image,filename);
        // window.location.href=image; // it will save locally  
	});
}, false);

</script>
    </head>
    <body>
        <div class="container" id="container">
            <section>				
                <div id="container_demo" >
                    <!-- hidden anchor to stop jump http://www.css3create.com/Astuce-Empecher-le-scroll-avec-l-utilisation-de-target#wrap4  -->
                    <a class="hiddenanchor" id="toregister"></a>								

                    <a class="hiddenanchor" id="tologin"></a>
                    <div id="wrapper">

                        <div id="login" class="animate form">
                            <h1>自拍一下</h1>
								<div>
								<video id="video" width="440" height="330" autoplay></video>
								</div>
									<a id="snap" class="normal_button">拍照</a>
                            		<a id="autophotograph" class="normal_button">5秒后自动拍摄</a>
									<a id="rephotograph" class="normal_button">重拍</a>
									<a href="#toregister" id="change" class="to_register">修改</a>
        <a href="http://www.sae.sina.com.cn">sae站点</a>

                        </div>
                       <div id="register" class="animate form">
                                <h1> 修改一下</h1> 
		                         <canvas id="canvas" name="mypic" width="440" height="330"></canvas>
					 <div id="chooseColor"></div>
								<div id="chooseSize"></div><br><br>
								<div>
								<a id="download" class="normal_button">下载到本地</a>
								<a id="share" class="normal_button">分享到本网站</a>
								<a href="paint/show.php" class="to_register" target="_blank"> 查看他人分享 </a>
								<a href="#tologin" class="to_register"> 重新拍摄 </a>
                                            <a href="http://www.sae.sina.com.cn">sae站点</a>
								</div>
                        </div>		
                    </div>
                </div>  
            </section>
        </div>
    </body>
    <script type="text/javascript" src="index.js"></script>
    <script>

</script>
</html>
body部分定义了这个页面的布局,具体的css就不再将了,主要由两个div组成,一个拍照的div与修改的div,里面定义了一些href连接,主要说的是script部分,这部分就是实现拍照的主要代码,我在拍照里定义了video标签,使得你可以通过摄像头看见自己动的时候电脑里的头像也在动,而对于拍照的话,你只需让video上的流pause就可以了。
就可以了,好的,基本原理就是这样,说一下每个连接按钮对应的具体代码。

1.拍照:(index.html)

	document.getElementById("snap").addEventListener("click", function() {
		clearTimeout(timer);
		video.pause();
	});
2.五秒后延迟拍照:(index.html)

	document.getElementById("autophotograph").addEventListener("click",function(){
		video.play();
		timer = setTimeout(function(){	
			video.pause();
		},5000);
	});

3. 重拍:(index.html)

	document.getElementById("rephotograph").addEventListener("click", function() {
		clearTimeout(timer);
		video.play();
	});

4.修改:(index.html)

	document.getElementById("change").addEventListener("click", function() {
		context.drawImage(video, 0, 0, 440, 330);
	});

5.sae站点(index.html)

啊哦~~link连接==

<a href="http://www.sae.sina.com.cn">sae站点</a>
6.下载到本地(index.js)

    $("#download").click(function() {
        var myCanvas = document.getElementById("canvas");
        var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        // window.location.href=image;
        var filename = 'paint_' + (new Date()).getTime() + '.png';
        //saveFile(image, filename);
        
        var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
        save_link.href = image;
        save_link.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      //  save_link.dispatchEvent(event);
    });

    7.分享到本站(index.js):ps把图片流上传到sae的stoarge里。

	document.getElementById("share").onclick=function(){
		  //Ajax提交数据
		  var xhr=new XMLHttpRequest;
		  xhr.open("POST","upload.php",true);
		  xhr.onreadystatechange=function(){
		    if(xhr.readyState!=4)return;
		  };
		  //从canvas中获取DataURL并发送
		  xhr.send(canvas.toDataURL());
          alert("分享成功!");
		};

8.查看他人分享:(paint/show.php)

        这个就是一个连接到paint/show.php页面,但是生成这个页面还是有些难度,如果使用本地文件来存储的话可以遍历图片文件下的所有图片,如果想做高级一点的话就可以实现动态加载,这个是遍历sae的一个stoarge上的所有图片,代码如下:

<?php
$fileTypes = array('jpg','jpeg','gif','png');
$width = 200;
$height = 200;
$pageTitle = "Pictures";
  
// *************************************************************
  $s = new SaeStorage();
$domain = 'takephoto';//我刚创建的domain的名称

$filelist = $s->getList($domain,"",100);

$f = join(',*.', $fileTypes);
$f = '*.'.$f;
$height += 20;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title><?php echo $pageTitle; ?></title>
    <script type="text/javascript" src="../js/jquery-1.8.3.js"></script>
	<script type="text/javascript" src="../js/jquery.popImage.mini.js"></script>
	<link rel="stylesheet" type="text/css" href="../css/popImage.css" />	
<style type="text/css">
<!--
* { margin:0; padding:0; }
h1 { background:#eee; font-weight:normal; padding:3px 5px; font-size:medium; }
ul { margin-top:10px; list-style:none; }
ul li { width:<?php echo $width; ?>px; height:<?php echo $height; ?>px; float:left; padding:5px; overflow:hidden; margin-bottom:10px; }
ul li span { height:20px; font-size:medium; font-style:italic; }
ul li a img { width:<?php echo $width; ?>px; border:dotted 1px #ddd; }

}
-->
</style>
  </head>
  <body>
    <ul>
<?php $loop = 1; foreach($filelist as $name) { ?>
      <li>
        <span><?php echo $loop; ?></span>
        <a href="<?php echo $s->getUrl($domain,$name); ?>" target="_blank" rel="gallery" class="image_gall"><img alt="<?php echo $s->getUrl($domain,$name); ?>" src="<?php echo $s->getUrl($domain,$name); ?>" /></a>
      </li>
<?php $loop++; } ?>
    </ul>
    <script>
    $(function(){
    	$("a.image_gall").popImage();
    	})
</script>
  </body>
</html>

说一下,图片的展开效果用的是popImage,简单却实用的小工具。

最后,GitHub的下载地址。https://github.com/saymagic/takephoto。有什么问题欢迎提出,若有改进,也欢迎大家多多开源。

                                     

                                     转载请注明:我的原博客链接http://blog.saymagic.cn/blog.php?id=4