Created
          July 26, 2021 12:41 
        
      - 
      
- 
        Save wobsoriano/ceafa14102d7911477f3bc7d4f5b2e02 to your computer and use it in GitHub Desktop. 
    SVG to Canvas
  
        
  
    
      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
    
  
  
    
  | export default async function svgToCanvas(svgElement: SVGElement): Promise<HTMLCanvasElement> { | |
| return new Promise((resolve, reject) => { | |
| const { width, height } = svgElement.getBoundingClientRect(); | |
| const blob = new Blob([svgElement.outerHTML], { type:'image/svg+xml' }) | |
| const blobURL = window.URL.createObjectURL(blob) | |
| const image = new Image() | |
| image.onload = () => { | |
| window.URL.revokeObjectURL(blobURL) | |
| const canvas = document.createElement('canvas') | |
| canvas.width = width | |
| canvas.height = height | |
| const ctx = canvas.getContext('2d') | |
| ctx?.drawImage(image, 0, 0, width, height) | |
| resolve(canvas) | |
| } | |
| image.onerror = () => { | |
| reject('Unable to convert svg to canvas') | |
| } | |
| image.src = blobURL | |
| }) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment