file+canvas实现图片展示和下载

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
  <div id="c"></div>
  <script>
    var div = document.getElementById('c')
    var fileselect = document.getElementById('fileselect')

    function downloadHandler(e) {
      var url = e.target.toDataURL();
      var a = document.createElement('a');
      a.href = url
      a.download = e.target.getAttribute('file-name').replace('.svg', '.png');
      a.click()
    }

    function handleFile(f) {
      //图片展示 和点击下载 
      var reader = new FileReader();
      var canvas = document.createElement('canvas');
      div.appendChild(canvas)
      reader.onload = function(e) {
        var image = new Image()
        image.onload = function() {
          canvas.setAttribute('file-name', f.name)
          canvas.addEventListener('click', downloadHandler);
          canvas.width = image.width
          canvas.height = image.height
          canvas.getContext('2d').drawImage(image, 0, 0)
        }
        image.src = e.target.result
      }
      reader.readAsDataURL(f)
    }

    function FileSelectHandler(e) {
      var files = e.target.files || e.dataTransfer.files //dataTransfer主要用于在源对象和目标对象之间传递数据
      for (var i = 0, f; f = files[i]; i++) {
        handleFile(f)
      }
    }
    //input添加监听事件
    fileselect.addEventListener('change', FileSelectHandler, false) //true - 事件句柄在捕获阶段执行  false- false- 默认。事件句柄在冒泡阶段执行
  </script>
</body>

</html>

 

posted @ 2022-03-30 16:51  聂小恶  阅读(88)  评论(0编辑  收藏  举报