Skip to content

Instantly share code, notes, and snippets.

@camman3d
Last active April 27, 2024 16:33
Show Gist options
  • Select an option

  • Save camman3d/314c07def1d6f728cd89ce0f49fc0ed1 to your computer and use it in GitHub Desktop.

Select an option

Save camman3d/314c07def1d6f728cd89ce0f49fc0ed1 to your computer and use it in GitHub Desktop.

Revisions

  1. camman3d revised this gist Aug 25, 2017. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions svg-to-png.js
    Original file line number Diff line number Diff line change
    @@ -3,8 +3,12 @@ function svgToPng(svg) {
    let svgData = new XMLSerializer().serializeToString(svg);
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    let img = document.createElement('img');
    img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(svgData));

    let DOMURL = window.URL || window.webkitURL || window;
    let img = new Image();
    let blog = new Blob([svgData], {type: 'image/svg+xml'});
    let url = DOMURL.createObjectURL(blog);

    return new Promise(resolve => {
    img.addEventListener('load', () => {
    canvas.width = img.width;
    @@ -13,5 +17,6 @@ function svgToPng(svg) {
    let url = canvas.toDataURL('image/png');
    resolve(url);
    });
    img.src = url;
    });
    }
  2. camman3d created this gist Aug 25, 2017.
    17 changes: 17 additions & 0 deletions svg-to-png.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    // let svg = document.querySelector('svg');
    function svgToPng(svg) {
    let svgData = new XMLSerializer().serializeToString(svg);
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    let img = document.createElement('img');
    img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(svgData));
    return new Promise(resolve => {
    img.addEventListener('load', () => {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0);
    let url = canvas.toDataURL('image/png');
    resolve(url);
    });
    });
    }