webtools/freelens-logo/script.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

(function() {
const canvas = document.getElementById('logoCanvas');
const ctx = canvas.getContext('2d');
const upperInput = document.getElementById('upperText');
const lowerInput = document.getElementById('lowerText');
const colorSelect = document.getElementById('bgColor');
const downloadBtn = document.getElementById('downloadBtn');
const PADDING = 15;
const LINE_WIDTH = 2;
function fitText(text, maxWidth, maxHeight) {
let size = maxHeight;
ctx.font = `bold ${size}px sans-serif`;
while (ctx.measureText(text).width > maxWidth && size > 8) {
size--;
ctx.font = `bold ${size}px sans-serif`;
}
return size;
}
function draw() {
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = colorSelect.value;
ctx.fillRect(0, 0, width, height);
const upper = upperInput.value;
const lower = lowerInput.value;
if (lower != "") {
ctx.strokeStyle = 'white';
ctx.lineWidth = LINE_WIDTH;
const yLine = height / 2;
ctx.beginPath();
ctx.moveTo(PADDING, yLine);
ctx.lineTo(width - PADDING, yLine);
ctx.stroke();
}
const availableWidth = width - PADDING * 2;
const availableHeight = height - PADDING * 2;
const halfHeight = availableHeight / 2;
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
if (lower != "") {
let fontSize = fitText(upper, availableWidth, halfHeight);
ctx.font = `bold ${fontSize}px sans-serif`;
ctx.fillText(upper, width / 2, PADDING + halfHeight / 2);
fontSize = fitText(lower, availableWidth, halfHeight);
ctx.font = `bold ${fontSize}px sans-serif`;
ctx.fillText(lower, width / 2, height - PADDING - halfHeight / 2 + 4);
} else {
let fontSize = fitText(upper, availableWidth, halfHeight);
ctx.font = `bold ${fontSize}px sans-serif`;
ctx.fillText(upper, width / 2, height / 2);
}
}
upperInput.addEventListener('input', draw);
lowerInput.addEventListener('input', draw);
colorSelect.addEventListener('change', draw);
downloadBtn.addEventListener('click', function() {
const link = document.createElement('a');
link.download = 'logo.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
draw();
})();