design-public/logo/svg2png_converter/converter.js

48 lines
1.4 KiB
JavaScript

let can = document.createElement("canvas");
let ctx = can.getContext("2d");
let result;
const renderButton = document.querySelector("#render");
const downloadButton = document.querySelector("#download");
function handleFileSelect(e) {
const files = e.target.files;
if (!files || !files.length) return;
const file = files[0];
if (file.type !== "image/svg+xml") return;
const reader = new FileReader();
reader.onload = (readerEvent) => {
renderSVG(readerEvent.target.result);
}
reader.readAsDataURL(file);
}
function renderSVG(base64SVG) {
const image = new Image();
const preview = document.querySelector("#preview");
image.onload = function () {
can.setAttribute("width", this.width);
can.setAttribute("height", this.height);
ctx.drawImage(image, 0, 0, this.width, this.height);
preview.src = result = can.toDataURL("image/png");
downloadButton.disabled = false;
}
image.src = base64SVG;
}
function downloadURI(_uri, _name) {
let link = document.createElement("a");
link.download = "render.png";
link.href = result;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
document.querySelector('#file_input').addEventListener('change', handleFileSelect, false);
downloadButton.addEventListener("click", downloadURI);