/* Basic Reset & Body Styling */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f6;
color: #333;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 20px;
}
/* Container */
.container {
background-color: #fff;
padding: 30px 40px;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 600px;
width: 100%;
}
h1 {
color: #2c3e50;
margin-bottom: 25px;
}
h2 {
color: #34495e;
margin-bottom: 15px;
border-bottom: 1px solid #eee;
padding-bottom: 5px;
}
/* Input and Controls */
.input-section,
.controls-section,
.output-section {
margin-bottom: 25px;
}
.input-section label,
.controls-section label,
.controls-section small {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #555;
}
#svgFileInput {
display: block;
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #fdfdfd;
}
.controls-section {
background-color: #ecf0f1;
padding: 20px;
border-radius: 6px;
}
.control-group {
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 10px; /* Space between label and input */
flex-wrap: wrap; /* Allow wrapping on small screens */
}
.control-group label {
min-width: 80px; /* Adjust as needed */
}
.control-group input[type="number"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 80px; /* Fixed width for numbers */
}
.control-group input[type="number"]:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.control-group.aspect-ratio-control {
margin-top: 15px;
justify-content: flex-start; /* Align checkbox group to the start */
flex-wrap: nowrap; /* Prevent wrapping for the checkbox label itself */
}
.control-group.aspect-ratio-control label {
display: inline-flex; /* Align checkbox and text */
align-items: center;
gap: 5px;
font-weight: normal;
color: #333;
margin-bottom: 0;
}
/* Buttons */
.convert-button, .download-button {
background-color: #3498db;
color: white;
border: none;
padding: 12px 25px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease, transform 0.2s ease;
margin-top: 10px;
}
.convert-button:hover, .download-button:hover {
background-color: #2980b9;
transform: translateY(-1px);
}
.convert-button:disabled {
background-color: #bdc3c7;
cursor: not-allowed;
}
/* Output Area */
#previewArea {
border: 1px dashed #ccc;
min-height: 100px;
padding: 15px;
margin-bottom: 20px;
display: flex;
justify-content: center;
align-items: center;
background-color: #fafafa;
border-radius: 4px;
overflow: hidden; /* Ensure image stays within bounds */
}
#previewArea img {
max-width: 100%;
max-height: 300px; /* Limit preview height */
height: auto;
display: block; /* Remove extra space below image */
}
#previewArea p {
color: #7f8c8d;
}
.status-message {
margin-top: 10px;
font-size: 0.9em;
min-height: 1.2em; /* Prevent layout shifts */
}
.status-message.error {
color: #e74c3c;
}
.status-message.success {
color: #2ecc71;
}
const svgFileInput = document.getElementById('svgFileInput');
const widthInput = document.getElementById('widthInput');
const heightInput = document.getElementById('heightInput');
const maintainAspectRatioCheckbox = document.getElementById('maintainAspectRatio');
const convertBtn = document.getElementById('convertBtn');
const previewArea = document.getElementById('previewArea');
const downloadLink = document.getElementById('downloadLink');
const statusMessage = document.getElementById('statusMessage');
let svgContent = null;
let originalWidth = 0;
let originalHeight = 0;
let currentSvgUrl = null; // To store the Object URL for potential cleanup
// --- Event Listeners ---
svgFileInput.addEventListener('change', handleFileSelect);
convertBtn.addEventListener('click', convertSvgToPng);
// Update height input if aspect ratio is maintained and width changes
widthInput.addEventListener('input', () => {
if (maintainAspectRatioCheckbox.checked && originalWidth > 0 && originalHeight > 0) {
const newWidth = parseInt(widthInput.value, 10);
if (!isNaN(newWidth) && newWidth > 0) {
const aspectRatio = originalHeight / originalWidth;
heightInput.value = Math.round(newWidth * aspectRatio);
}
}
});
// Update width input if aspect ratio is maintained and height changes
heightInput.addEventListener('input', () => {
if (maintainAspectRatioCheckbox.checked && originalWidth > 0 && originalHeight > 0) {
const newHeight = parseInt(heightInput.value, 10);
if (!isNaN(newHeight) && newHeight > 0) {
const aspectRatio = originalWidth / originalHeight;
widthInput.value = Math.round(newHeight * aspectRatio);
}
}
});
// --- Functions ---
function handleFileSelect(event) {
const file = event.target.files[0];
resetState(); // Clear previous results
if (!file) {
setStatus('No file selected.', 'error');
return;
}
if (file.type !== 'image/svg+xml') {
setStatus('Invalid file type. Please upload an SVG.', 'error');
svgFileInput.value = ''; // Clear the input
return;
}
const reader = new FileReader();
reader.onload = function(e) {
svgContent = e.target.result;
// Try to extract original dimensions (optional, useful for aspect ratio)
// This regex is basic and might fail on complex inline styles or attributes
const widthMatch = svgContent.match(/width="(\d+(\.\d+)?)/i);
const heightMatch = svgContent.match(/height="(\d+(\.\d+)?)/i);
originalWidth = widthMatch ? parseFloat(widthMatch[1]) : 0;
originalHeight = heightMatch ? parseFloat(heightMatch[1]) : 0;
// If dimensions aren't found in SVG, try viewBox as a fallback
if (!originalWidth || !originalHeight) {
const viewBoxMatch = svgContent.match(/viewBox="(\d+(\.\d+)?)\s+(\d+(\.\d+)?)\s+(\d+(\.\d+)?)\s+(\d+(\.\d+)?)/i);
if (viewBoxMatch) {
// viewBox="x y width height" - we only need width/height here
originalWidth = viewBoxMatch[5] ? parseFloat(viewBoxMatch[5]) : 0;
originalHeight = viewBoxMatch[7] ? parseFloat(viewBoxMatch[7]) : 0;
}
}
// Set default inputs based on SVG if possible
if (widthMatch && !widthInput.value) {
widthInput.value = originalWidth > 0 ? Math.round(originalWidth) : 512;
}
if (heightMatch && !heightInput.value) {
heightInput.value = originalHeight > 0 ? Math.round(originalHeight) : 512;
}
setStatus('SVG loaded successfully. Ready to convert.', 'success');
convertBtn.disabled = false; // Enable the convert button
};
reader.onerror = function() {
setStatus('Error reading file.', 'error');
svgContent = null;
convertBtn.disabled = true;
};
reader.readAsText(file); // Read SVG as text
}
function convertSvgToPng() {
if (!svgContent) {
setStatus('Please upload an SVG file first.', 'error');
return;
}
const targetWidth = parseInt(widthInput.value, 10);
const targetHeight = parseInt(heightInput.value, 10);
if (isNaN(targetWidth) || targetWidth <= 0) {
setStatus('Please enter a valid positive width.', 'error');
return;
}
if (isNaN(targetHeight) || targetHeight <= 0) {
setStatus('Please enter a valid positive height.', 'error');
return;
}
// Create a Blob and Object URL for the SVG
// Using Blob/ObjectURL is generally more reliable than data URIs for complex SVGs
const svgBlob = new Blob([svgContent], { type: 'image/svg+xml;charset=utf-8' });
currentSvgUrl = URL.createObjectURL(svgBlob);
const svgImage = new Image();
svgImage.onload = function() {
// Create canvas
const canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
// Draw the SVG image onto the canvas
ctx.drawImage(svgImage, 0, 0, targetWidth, targetHeight);
// Convert canvas to PNG Data URL
try {
const pngUrl = canvas.toDataURL('image/png');
// Update preview
const imgElement = document.createElement('img');
imgElement.src = pngUrl;
previewArea.innerHTML = ''; // Clear previous preview
previewArea.appendChild(imgElement);
// Update download link
downloadLink.href = pngUrl;
// Try to get a meaningful filename
const filename = svgFileInput.files.length > 0
? svgFileInput.files[0].name.replace(/\.svg$/i, `_${targetWidth}x${targetHeight}.png`)
: `converted_${targetWidth}x${targetHeight}.png`;
downloadLink.download = filename;
downloadLink.style.display = 'inline-block'; // Show download link
setStatus('Conversion successful!', 'success');
} catch (e) {
setStatus('Error converting to PNG. Ensure SVG is valid.', 'error');
console.error("Canvas toDataURL error:", e);
} finally {
// Clean up the object URL once the image is loaded/drawn
if (currentSvgUrl) {
URL.revokeObjectURL(currentSvgUrl);
currentSvgUrl = null;
}
}
};
svgImage.onerror = function() {
setStatus('Error rendering SVG. Check SVG content.', 'error');
if (currentSvgUrl) {
URL.revokeObjectURL(currentSvgUrl);
currentSvgUrl = null;
}
};
// Set the src for the image object using the Object URL
svgImage.src = currentSvgUrl;
}
function setStatus(message, type = 'info') {
statusMessage.textContent = message;
statusMessage.className = `status-message ${type}`; // Reset classes and add type
}
function resetState() {
svgContent = null;
originalWidth = 0;
originalHeight = 0;
previewArea.innerHTML = '<p>Upload an SVG and click "Convert to PNG" to see the result here.</p>';
downloadLink.style.display = 'none';
downloadLink.href = '#';
downloadLink.download = 'converted.png';
convertBtn.disabled = true;
setStatus(''); // Clear status message
}
// Initialize button state
convertBtn.disabled = true;