vue實現pc端拍照上傳功能

本文實例為大傢分享瞭vue實現pc端拍照上傳功能的具體代碼,供大傢參考,具體內容如下

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF8">
  </head> 
  <body>  
 
<div id="contentHolder">       
<video id="video" width="320" height="320" autoplay></video>       
<button id="camera">拍照</button>        
<canvas id="canvas" width="320" height="320">
</canvas> 
</div>
 
<script type="text/javascript">  
var video = document.getElementById('video');
var track;
var Camera= document.getElementById('camera');
 window.addEventListener("DOMContentLoaded", function(){
 navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  if (navigator.getUserMedia) {
    navigator.getUserMedia({video:true},
     function(stream) {
      track = stream.getTracks()[0];  // 通過這個關閉攝像頭
      video.src = window.URL.createObjectURL(stream);
      video.onloadedmetadata = function(e) {
           video.play();
         };
     },
     function(err) {
        alert(err.name);
     }
    );
  }  
 
  
 });   
 
 
Camera.onclick = function(){
 var canvas = document.getElementById('canvas');
 var context2D = canvas.getContext("2d");
 context2D.fillStyle = "#ffffff";
 context2D.fillRect(0, 0, 320, 320);
 context2D.drawImage(video, 0, 0, 320, 320);
 var image_code =canvas.toDataURL("image/png");//要傳給後臺的base64
 
 console.log(image_code)
 if (null != track) {
            track.stop();//關閉攝像頭
      }
 
};
</script>
  </body> 
</html>

上段代碼會在打開網頁的時候就會調用攝像頭

傳給後臺的是個base64碼

下面是我用vue傳給後臺的代碼

var param = {
 file:image_code2
 }
 var a = JSON.stringify(param);
 
 uploadimg(a).then((res) => {
     console.log(res);
          
 });

下面是我的php後臺接收代碼

public function uploadImg($name="img",$path='img'){
        $_POST = json_decode(file_get_contents('php://input'),true);
        $param = $_POST;
        $image_code = $param['file'];
        $img = str_replace('data:image/png;base64,', '', $image_code);//獲取base64碼
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $name = time().".png";
        $savepath = "./upload/".$name;//將圖片存到的位置
        file_put_contents($savepath,$data);//將內容寫入文件
        $this->ajaxReturn(array('status'=>'0','data'=>$savepath));
    }

如果想點擊觸發 打開攝像頭可以將camera中代碼取出放在一個方法中即可

var Camera= document.getElementById('camera');
 window.addEventListener("DOMContentLoaded", function(){
 navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; 
  
 });   
 
function demo(){
 if (navigator.getUserMedia) {
    navigator.getUserMedia({video:true},
     function(stream) {
      track = stream.getTracks()[0];  // 通過這個關閉攝像頭
      video.src = window.URL.createObjectURL(stream);
      video.onloadedmetadata = function(e) {
           video.play();
         };
     },
     function(err) {
        alert(err.name);
     }
    );
  }  
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: