<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="favicon.png">
<title></title>
<meta name="description" content="" />
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
canvas {
border: 1px solid black;
}
img {
border: 1px solid black;
}
</style>
</head>
<body>
<a href="" download="">Download PNG</a>
<canvas width="0" height="0"></canvas>
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="300px" height="300px">
<circle cx="50" cy="50" r="25" fill="blue" stroke="red" />
</svg>
<script src="script.js"></script>
</body>
</html>
function encodeSvg(svgString) {
return svgString.replace(/"/g, '\'')
.replace(/%/g, '%25')
.replace(/#/g, '%23')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/\s+/g, ' ');
}
function toPNG(id) {
var svg = document.getElementById(id);
var xml = encodeSvg(svg.outerHTML);
var img = new Image();
canvas.width = svg.clientWidth;
canvas.height = svg.clientHeight;
img.width = svg.clientWidth;
img.height = svg.clientHeight;
var svgStr = 'data:image/svg+xml,' + xml;
img.src = svgStr;
img.onload = () => {
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
var a = document.querySelector('a');
a.setAttribute('href',dataURL);
a.setAttribute('download','image.png');
}
}
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
toPNG('svg1');
Convert an inline SVG element into a downloadable PNG image.
To view this on TripleLog, click here.