Created
          April 6, 2020 05:17 
        
      - 
      
- 
        Save wobsoriano/e05ced7fd464e559e5042449e96c3b79 to your computer and use it in GitHub Desktop. 
    Download external image on button click
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function downloadImage(data, filename = 'untitled.jpeg') { | |
| var a = document.createElement('a'); | |
| a.href = data; | |
| a.download = filename; | |
| document.body.appendChild(a); | |
| a.click(); | |
| } | |
| document.getElementById('btn-download').addEventListener("click", function(e) { | |
| const canvas = document.createElement('canvas'); | |
| const ctx = canvas.getContext('2d'); | |
| const img = new Image(); | |
| img.crossOrigin = ''; | |
| img.src = "https://robohash.org/robert" | |
| img.onload = function() { | |
| const img = this; | |
| canvas.width = img.width; | |
| canvas.height = img.height; | |
| ctx.drawImage(img, 0, 0, img.width, img.height); | |
| const dataURL = canvas.toDataURL(); | |
| downloadImage(dataURL, 'my-canvas.jpeg'); | |
| } | |
| }); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment