Skip to content

Commit

Permalink
Merge pull request #552 from nounsDAO/soli-fix-playground-png-render
Browse files Browse the repository at this point in the history
Fix Playground PNG Rendering
  • Loading branch information
solimander authored Aug 29, 2022
2 parents 13d44e3 + dcb6d67 commit 0a96001
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
27 changes: 22 additions & 5 deletions packages/nouns-webapp/src/utils/svg2png.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@
*/
export const svg2png = (
svgString: string,
newWidth: number = 320,
newHeight: number = 320,
newWidth = 320,
newHeight = 320,
): Promise<string | null> => {
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;
Expand All @@ -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;
};

0 comments on commit 0a96001

Please sign in to comment.