Created
February 1, 2023 12:54
-
-
Save cshotton/f297f3e18cc0725f05ce7880750011e4 to your computer and use it in GitHub Desktop.
One page app to view SVG source as image and PNG download
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
<html> | |
<head> | |
<title>myByways SVG to PNG Converter</title> | |
</head> | |
<body bgcolor="#E6E6FA"> | |
<h1><a href="http://mybyways.com/blog/convert-svg-to-png-using-your-browser">myByways SVG to PNG Converter</a></h1> | |
<textarea id="t" rows="8" cols="70"></textarea><br/><br/> | |
<button id="l">Load SVG</button><br/><br/> | |
<div id="d"></div><br/> | |
Width: <input id="w" type="number" max="9999"></input> | |
Height: <input id="h" type="number" max="9999"></input><br/> | |
<button id="s">Save SVG as PNG</button><br/><br/> | |
<canvas id="c"></canvas> | |
<script> | |
/* SVG to PNG (c) 2017 CY Wong / myByways.com */ | |
var text = document.getElementById('t'); | |
text.wrap = 'off'; | |
var svg = null; | |
var width = document.getElementById('w'); | |
var height = document.getElementById('h'); | |
document.getElementById('l').addEventListener('click', function () { | |
var div = document.getElementById('d'); | |
div.innerHTML= text.value; | |
svg = div.querySelector('svg'); | |
width.value = svg.getBoundingClientRect().width; | |
height.value = svg.getBoundingClientRect().height; | |
}); | |
document.getElementById('s').addEventListener('click', function () { | |
var canvas = document.getElementById('c'); | |
svg.setAttribute('width', width.value); | |
svg.setAttribute('height', height.value); | |
canvas.width = width.value; | |
canvas.height = height.value; | |
var data = new XMLSerializer().serializeToString(svg); | |
var win = window.URL || window.webkitURL || window; | |
var img = new Image(); | |
var blob = new Blob([data], { type: 'image/svg+xml' }); | |
var url = win.createObjectURL(blob); | |
img.onload = function () { | |
canvas.getContext('2d').drawImage(img, 0, 0); | |
win.revokeObjectURL(url); | |
var uri = canvas.toDataURL('image/png').replace('image/png', 'octet/stream'); | |
var a = document.createElement('a'); | |
document.body.appendChild(a); | |
a.style = 'display: none'; | |
a.href = uri | |
a.download = (svg.id || svg.svg.getAttribute('name') || svg.getAttribute('aria-label') || 'untitled') + '.png'; | |
a.click(); | |
window.URL.revokeObjectURL(uri); | |
document.body.removeChild(a); | |
}; | |
img.src = url; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment