From 7e6f8a14da9a99ced60a57b15ebad55d4d552b0e Mon Sep 17 00:00:00 2001 From: LitoMore Date: Tue, 27 Aug 2024 00:23:24 +0800 Subject: [PATCH] Add support for customizing icon size --- README.md | 4 ++++ source/app.js | 4 ++-- source/icon.js | 28 ++++++++++++++++++++++++++-- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 69876f3..2cc5e96 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,10 @@ Optional. It's used for dark mode and has the same function as `color`. The [CSS Optional. The icon is placed in a square viewBox by default. Use the query parameter `viewbox=auto` to adjust the viewBox to the same aspect ratio as the shape. +#### `size` + +Optional. It's used for customizing the icon size. Icon will be scaled with its original aspect ratio. + ### Examples - - https://cdn.simpleicons.org/simpleicons diff --git a/source/app.js b/source/app.js index c6b7611..173b7be 100644 --- a/source/app.js +++ b/source/app.js @@ -35,10 +35,10 @@ router.get("/:iconSlug/:color?/:darkModeColor?", (ctx) => { cacheForSevenDays(ctx); const { iconSlug, color, darkModeColor } = ctx.params; const viewbox = ctx.request.url.searchParams.get("viewbox"); + const size = ctx.request.url.searchParams.get("size"); const icon = getSimpleIcon(iconSlug); - if (icon) { - const iconSvg = getIconSvg(icon, color, darkModeColor, viewbox); + const iconSvg = getIconSvg(icon, color, darkModeColor, viewbox, size); ctx.response.headers.set("Content-Type", "image/svg+xml"); ctx.response.body = iconSvg; return; diff --git a/source/icon.js b/source/icon.js index 5627c27..439e1ae 100644 --- a/source/icon.js +++ b/source/icon.js @@ -47,14 +47,19 @@ export const resetIconPosition = (path, iconWidth, iconHeight) => { return { path: pathReset, betterViewboxWidth }; }; -export const getIconSvg = (icon, color = "", darkModeColor = "", viewbox) => { +export const getIconSvg = ( + icon, + color = "", + darkModeColor = "", + viewbox, + size, +) => { const hex = normalizeColor(color) || `#${icon.hex}`; const darkModeHex = normalizeColor(darkModeColor) || `#${icon.hex}`; let iconSvg = icon.svg; if (viewbox === "auto") { const { width: iconWidth, height: iconHeight } = getIconSize(icon.path); - const { path, betterViewboxWidth } = resetIconPosition( icon.path, iconWidth, @@ -68,6 +73,25 @@ export const getIconSvg = (icon, color = "", darkModeColor = "", viewbox) => { .replace(//, ``); } + const iconSize = parseInt(size, 10); + if (iconSize && iconSize > 0) { + const sizePattern = /viewBox="0 0 (?\d+) (?\d+)"/; + const sizeMatch = sizePattern.exec(iconSvg); + const width = sizeMatch?.groups?.width; + const height = sizeMatch?.groups?.height; + if (Number(width) && Number(height)) { + const maxScale = (2 ** 14 - 1) / 24; + const minScale = 3 / 24; + const scale = Math.max(Math.min(maxScale, iconSize / 24), minScale); + const iconWidth = Math.round(width * scale); + const iconHeight = Math.round(height * scale); + iconSvg = iconSvg.replace( + "