Skip to content

Commit

Permalink
useImageの処理軽く
Browse files Browse the repository at this point in the history
  • Loading branch information
mehm8128 committed Mar 23, 2024
1 parent cbca77f commit f5446e3
Showing 1 changed file with 8 additions and 42 deletions.
50 changes: 8 additions & 42 deletions workspaces/app/src/foundation/hooks/useImage.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,12 @@
import { useAsync } from 'react-use';

import { getImageUrl } from '../../lib/image/getImageUrl';

export const useImage = ({ height, imageId, width }: { height: number; imageId: string; width: number }) => {
const { value } = useAsync(async () => {
const dpr = window.devicePixelRatio;

const img = new Image();
img.src = getImageUrl({
format: 'jpg',
height: height * dpr,
imageId,
width: width * dpr,
});

await img.decode();

const canvas = document.createElement('canvas');
canvas.width = width * dpr;
canvas.height = height * dpr;
const ctx = canvas.getContext('2d')!;

// Draw image to canvas as object-fit: cover
const imgAspect = img.naturalWidth / img.naturalHeight;
const targetAspect = width / height;

if (imgAspect > targetAspect) {
const srcW = img.naturalHeight * targetAspect;
const srcH = img.naturalHeight;
const srcX = (img.naturalWidth - srcW) / 2;
const srcY = 0;
ctx.drawImage(img, srcX, srcY, srcW, srcH, 0, 0, width * dpr, height * dpr);
} else {
const srcW = img.naturalWidth;
const srcH = img.naturalWidth / targetAspect;
const srcX = 0;
const srcY = (img.naturalHeight - srcH) / 2;
ctx.drawImage(img, srcX, srcY, srcW, srcH, 0, 0, width * dpr, height * dpr);
}

return canvas.toDataURL('image/png');
}, [height, imageId, width]);

return value;
const dpr = window.devicePixelRatio;

return getImageUrl({
format: 'jpg',
height: height * dpr,
imageId,
width: width * dpr,
});
};

0 comments on commit f5446e3

Please sign in to comment.