Last active
January 27, 2018 21:23
-
-
Save adieuadieu/635c7895cca069fefcfa8c7ea015d39b to your computer and use it in GitHub Desktop.
Grabs all SVGs matching a query selector from a webpage's DOM and converts them to a raster format (PNG), then downloads them
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
/* | |
Grabs all SVGs matching a query selector from a webpage's | |
DOM and converts them to a raster format (PNG), then downloads them. | |
I wanted to grab an <svg /> from a webpage. | |
Then, I realised I wanted it as a PNG. | |
So I wrote this script. Paste it into your browser's console. | |
*/ | |
((svgQuerySelector = 'svg', saveType = 'image/png', saveQuality = 1) => { | |
const svgElements = document.querySelectorAll(svgQuerySelector) | |
function download (dataUrl) { | |
const a = document.createElement('a') | |
a.href = dataUrl | |
a.download = 'svg' | |
a.target = '_blank' | |
a.id = 'foobar' | |
document.body.append(a) | |
a.click() | |
document.body.querySelector('#foobar').remove() | |
} | |
svgElements.forEach(svgElement => { | |
const svgXml = (new XMLSerializer).serializeToString(svgElement) | |
const svgDataUrl = `data:image/svg+xml,${encodeURIComponent(svgXml)}` | |
const canvas = document.createElement('canvas') | |
const canvasContext = canvas.getContext('2d') | |
const image = new Image() | |
canvas.width = parseInt(svgElement.getAttribute('width')) | |
canvas.height = parseInt(svgElement.getAttribute('height')) | |
image.onload = () => { | |
canvasContext.drawImage(image, 0, 0) | |
const imageDataUrl = canvas.toDataURL(saveType, saveQuality) | |
download(imageDataUrl) | |
} | |
image.src = svgDataUrl | |
download(svgDataUrl) | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment