如何使用 vanilla javascript 在 HTML canvas 上拖放和预览图像文件?

How to drag - drop and preview an image file on HTML canvas with vanilla javascript?

我想制作一个在线过滤器网络应用程序。所以我制作了一些滤镜效果并在 <div> 上拖放上传(带预览)但是当应用滤镜时我无法下载它(使用下载按钮)因为我不知道屏幕截图 API 或 <svg>。所以我想在 <canvas> 上绘制图像,因为我知道如何从 <canvas> 下载过滤后的图像,但似乎拖放功能如果我使用它就不再起作用或者我不知道如何使用拖动效果(比如拖动它会产生效果以及拖动离开会删除效果)并且也不知道如何放下<canvas> 上的图像。我只是在下面给出我的代码的某些部分。 [注意:我还添加了一个按钮来上传图像,您可以在下方 HTML 中看到该功能与拖放图像功能相同]

     dropzone.ondragover = function (){
    
        this.className = "drop__zone can__over";
         dropzone2.style.display = "none";
         
        return false;
    };

dropzone.ondragleave = function(){
 
    this.className = "drop__zone";
    dropzone2.style.display = "block";
    
    return false;
};

dropzone.ondrop = function (e){
     
    e.preventDefault();
    e.stopPropagation();
    this.className = "drop__zone";
    dropzone2.style.display = "none";
     dropzone2.style.border = "none";
    
    update(e.dataTransfer.files[0]);
};

var update = function(file){
    var reader = new FileReader();
    reader.readAsDataURL(file);
    
    reader.onload = ()=>{
       
        img.src = reader.result;
        img.style.maxHeight = "480px";
        img.style.maxWidth = "640px";
        dropzone.style.backgroundColor = "transparent";
      
        
       dropzone.appendChild(img);
   return false;     
    };
   
};
  <div class="drop__zone" id="drop__zone"></div>


    <div class="dropzone" id="drop__zone">
       <a  id="download_link" download="edited.jpg"  href=""></a>
        <span class="dropzone__span">
            Drag a Image Here <br>or<br>
        </span><br>
        <input type="file" id="mainup" multiple="false" accept="image/*" class="fileinput">
        <label for="mainup" class="btn__label" id="lab1">Upload a Picture</label>

</div>

这是一个非常基本的示例,说明了一种接受拖放图像的方法,将其绘制在带有滤镜的 canvas 上,并允许右击以使用应用过滤器:

<!DOCTYPE html>
<body>
  <input type='file' />
  <canvas></canvas>
</body>
<script>
  document.querySelector('input').addEventListener('drop', e => {
    e.preventDefault();
    const reader = new FileReader();
    reader.readAsDataURL(e.dataTransfer.files[0]);
    reader.onload = () => {
      const image = new Image();
      image.src = reader.result;
      image.onload = () => {
        const canvas = document.querySelector('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.filter = 'blur(10px)';
        context.drawImage(image, 0, 0);
      }
    }
  });
</script>
</html>