Created
October 7, 2024 01:11
-
-
Save jbnv/c80bf59bea5dbcc3a13a4eba1b9b5957 to your computer and use it in GitHub Desktop.
Script I use to save an SVG image on an HTML page as a PNG, JPG or WEBP image.
This file contains 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
const dataHeader = 'data:image/svg+xml;charset=utf-8'; | |
const $svg = document.getElementById('svg-container').querySelector('svg'); // <svg> element to save | |
const $holder = document.getElementById('img-container'); // <div> element | |
const destroyChildren = $element => { | |
while ($element.firstChild) { | |
const $lastChild = $element.lastChild ?? false | |
if ($lastChild) $element.removeChild($lastChild) | |
} | |
} | |
const loadImage = async url => { | |
const $img = document.createElement('img') | |
$img.src = url | |
return new Promise((resolve, reject) => { | |
$img.onload = () => resolve($img) | |
$img.onerror = reject | |
}) | |
} | |
const serializeAsXML = $e => (new XMLSerializer()).serializeToString($e) | |
const encodeAsUTF8 = s => `${dataHeader},${encodeURIComponent(s)}` | |
const convertSVGtoImg = async e => { | |
const $btn = e.target | |
const format = $btn.dataset.format ?? 'png' | |
destroyChildren($holder) | |
const svgData = encodeAsUTF8(serializeAsXML($svg)) | |
const img = await loadImage(svgData) | |
// https://www.w3schools.com/jsref/dom_obj_canvas.asp | |
const $canvas = document.createElement('canvas') | |
$canvas.width = $svg.clientWidth | |
$canvas.height = $svg.clientHeight | |
$canvas.getContext('2d').drawImage(img, 0, 0, $svg.clientWidth, $svg.clientHeight) | |
const $img = new Image($svg.clientWidth, $svg.clientHeight); | |
$img.src = await $canvas.toDataURL(`image/${format}`, 1.0); | |
$holder.appendChild($img); | |
} | |
const buttons = [...document.querySelectorAll('[data-format]')] | |
for (const btn of buttons) { | |
btn.onclick = convertSVGtoImg | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment