基于Html5的網頁大頭貼

jopen 12年前發布 | 50K 次閱讀 HTML5 前端技術

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 >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 >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 >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.csdn.net/saymagic/article/details/17782903

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!