72 lines
2.8 KiB
HTML
72 lines
2.8 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>SVG to Canvas</title>
|
|
</head>
|
|
<body>
|
|
<span>Scale value: <input type="text" id="scale" value="1.0"/></span>
|
|
<div id="drophere" style="width: 300px; height: 300px; border: 1px dashed black; text-align: center; vertical-align: middle;">
|
|
Drop an SVG file here to convert it to PNG!
|
|
</div>
|
|
<script>
|
|
const drophere = document.getElementById('drophere');
|
|
drophere.addEventListener('dragover', function(e) {
|
|
e.preventDefault();
|
|
});
|
|
|
|
drophere.addEventListener('drop', function(e) {
|
|
e.preventDefault();
|
|
const file = e.dataTransfer.files[0];
|
|
const reader = new FileReader();
|
|
reader.onload = function(e) {
|
|
const svgString = e.target.result;
|
|
const svgBlob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
|
|
|
|
const url = URL.createObjectURL(svgBlob);
|
|
|
|
const img = new Image();
|
|
img.onload = function() {
|
|
scaleElement = document.getElementById('scale');
|
|
scaleValue = parseFloat(scaleElement.value);
|
|
|
|
// If the scale value is not a number, default to 1.0
|
|
if (isNaN(scaleValue)) {
|
|
scaleValue = 1.0;
|
|
scaleElement.value = scaleValue;
|
|
}
|
|
|
|
const parser = new DOMParser();
|
|
const svgDoc = parser.parseFromString(svgString, 'image/svg+xml');
|
|
const svgElement = svgDoc.documentElement;
|
|
svgElement.setAttribute('width', img.width * scaleValue);
|
|
svgElement.setAttribute('height', img.height * scaleValue);
|
|
|
|
var canvas = document.createElement('canvas');
|
|
canvas.id = "CursorLayer";
|
|
canvas.width = img.width * scaleValue;
|
|
canvas.height = img.height * scaleValue;
|
|
canvas.style.zIndex = 8;
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
const pngUrl = canvas.toDataURL('image/png');
|
|
|
|
const downloadLink = document.createElement('a');
|
|
downloadLink.href = pngUrl;
|
|
downloadLink.download = file.name.replace(/svg$/,'png')
|
|
|
|
downloadLink.click();
|
|
downloadLink.remove();
|
|
|
|
URL.revokeObjectURL(url);
|
|
};
|
|
|
|
img.src = url;
|
|
};
|
|
reader.readAsText(file);
|
|
});
|
|
</script>
|
|
</body>
|
|
</html> |