Created
August 12, 2024 15:56
-
-
Save mfyz/463d273d501e4da2653c7bd300a6cbf1 to your computer and use it in GitHub Desktop.
svg to png - vanilla js
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="https://about.me/john.theodoropoulos">Online SVG to PNG Converter</a></h1> | |
<p>(1).Paste your SVG code here</p> | |
<textarea id="t" rows="8" cols="70"></textarea><br/><br/> | |
<button id="l">(2).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">(3).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