diff --git a/packages/nouns-webapp/src/pages/Playground/NounModal/index.tsx b/packages/nouns-webapp/src/pages/Playground/NounModal/index.tsx index 6fdf27b9ea..c67963cbbc 100644 --- a/packages/nouns-webapp/src/pages/Playground/NounModal/index.tsx +++ b/packages/nouns-webapp/src/pages/Playground/NounModal/index.tsx @@ -29,7 +29,7 @@ const NounModal: React.FC<{ onDismiss: () => void; svg: string }> = props => { window.addEventListener('resize', handleWindowSizeChange); const loadPng = async () => { - setPng(await svg2png(svg, 500, 500)); + setPng(await svg2png(svg, 512, 512)); }; loadPng(); diff --git a/packages/nouns-webapp/src/utils/svg2png.ts b/packages/nouns-webapp/src/utils/svg2png.ts index f67d71ac2f..1444b32ca6 100644 --- a/packages/nouns-webapp/src/utils/svg2png.ts +++ b/packages/nouns-webapp/src/utils/svg2png.ts @@ -6,16 +6,20 @@ */ export const svg2png = ( svgString: string, - newWidth: number = 320, - newHeight: number = 320, + newWidth = 320, + newHeight = 320, ): Promise => { return new Promise(resolve => { - var parser = new DOMParser(); - var doc = parser.parseFromString(svgString, 'image/svg+xml'); + const parser = new DOMParser(); + const doc = parser.parseFromString(svgString, 'image/svg+xml'); const modSvg = doc.documentElement; const width = Number(modSvg.getAttribute('width')); const height = Number(modSvg.getAttribute('height')); + if (!canScale(width, newWidth) || !canScale(height, newHeight)) { + throw new Error(`Unable to scale canvas without unwanted pixel gap`); + } + const canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; @@ -34,10 +38,23 @@ export const svg2png = ( try { resolve(png); } catch (e) { - console.log('error converting svg to png: ', e); + console.log('Error converting SVG to PNG:', e); resolve(null); } }; img.src = url; }); }; + +/** + * Determine if the image can be scaled without creating a pixel gap. + * This will occur if the `desired` pixel length divided by the `current` + * pixel length has more than one decimal place. + * @param current The current pixel length + * @param desired The desired pixel length + */ +const canScale = (current: number, desired: number) => { + const result = desired / current; + const decimals = result.toString().split('.')?.[1]?.length ?? 0; + return decimals <= 1; +};