js利用clipboardData在網頁中實現截屏粘貼的功能

最近在作一個將屏幕截圖直接粘貼發送的功能,因而對此作了一些研究,下面是具體的實現代碼:
html代碼以下,在這裏只是簡單的作了一個textare框用做演示html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>截屏粘貼</title>
</head>
<body>
  <textarea onpaste ="paste()">
  </textarea>
</body>
</html>

具體實如今JavaScript中:前端

function paste(event){
  var clipboardData = event.clipboardData;
  console.log(clipboardData);
  var items,item,types;
  if( clipboardData ){
    items = clipboardData.items;
    if( !items ){
      return;
    }
    // 保存在剪貼板中的數據類型
    types = clipboardData.types || [];
    for(var i=0 ; i < types.length; i++ ){
      if( types[i] === 'Files' ){
        item = items[i];
        break;
      }
    }
    // 判斷是否爲圖片數據
    if( item && item.kind === 'file' && item.type.match(/^image\//i) ){
      // 讀取該圖片
      var file = item.getAsFile(),
          reader = new FileReader();
      reader.readAsDataURL(file);
      console.log(reader);
      //下面是講粘貼的圖片內容傳送到後端進行處理,若是直接前端處理能夠不要後邊的代碼
      var xhr = new XMLHttpRequest();
      xhr.open('post', '/pasteImage',true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      reader.onload = function(){
        console.log(reader.result);
        xhr.send(JSON.stringify({
          file: reader.result
        }));
      };
      //接收返回數據
      xhr.onload = function(){
        var response = JSON.parse(xhr.responseText);
        if(response.code == 200){
        //
        }else{
        //
        }
      }
    }
  }
}
相關文章
相關標籤/搜索