From 57e13a7eb4afc8e6136b363d5d9bbb932fd2d0f9 Mon Sep 17 00:00:00 2001 From: Florian Gauger Date: Sat, 20 Apr 2024 16:17:59 +0200 Subject: [PATCH] Properly center favicon --- src/js/draw.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/js/draw.js b/src/js/draw.js index b13c2f6..995d3c3 100644 --- a/src/js/draw.js +++ b/src/js/draw.js @@ -35,24 +35,38 @@ function setFont(icon, size) { ctx.font = fontWeight + ' ' + (icon.si * size) / 100 + 'px "Font Awesome 5 ' + fontSuffix + '"'; } +function fillText(text) { + const textMetrics = ctx.measureText(text); + const horizontalAdjustment = (textMetrics.actualBoundingBoxLeft - textMetrics.actualBoundingBoxRight) / 2; + const verticalAdjustment = (textMetrics.actualBoundingBoxAscent - textMetrics.actualBoundingBoxDescent) / 2; + const horizontalCenter = canvasSize / 2 + horizontalAdjustment; + const verticalCenter = canvasSize / 2 + verticalAdjustment; + + ctx.fillText(text, horizontalCenter, verticalCenter); +} + function draw() { if (canvasSize > 0) { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = s.backgroundColor; ctx.fillRect(0, 0, canvas.width, canvas.height); setFont(s.icon, s.size); + ctx.fillStyle = 'rgba(0, 0, 0, 1)'; ctx.globalCompositeOperation = 'destination-out'; - ctx.fillText(s.icon.uc, canvasSize / 2, canvasSize / 2); + fillText(s.icon.uc); + ctx.fillStyle = s.foregroundColor; ctx.globalCompositeOperation = 'source-over'; + fillText(s.icon.uc); - ctx.fillText(s.icon.uc, canvasSize / 2, canvasSize / 2); if (s.stackedSelected) { ctx.save(); + setFont(s.stackedIcon, s.stackedSize); ctx.globalCompositeOperation = 'xor'; - ctx.fillText(s.stackedIcon.uc, canvasSize / 2, canvasSize / 2); + fillText(s.stackedIcon.uc); + ctx.restore(); } canvasToFavicon(canvas);