mirror of
https://github.com/aljazceru/rabbit.git
synced 2025-12-17 22:14:26 +01:00
53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import { createSignal, createEffect } from 'solid-js';
|
|
import type { Accessor } from 'solid-js';
|
|
|
|
export type UseResizedImageProps = {
|
|
imageUrl: Accessor<string | undefined>;
|
|
width: number;
|
|
height: number;
|
|
encoderOptions?: number;
|
|
};
|
|
|
|
const useResizedImage = ({
|
|
imageUrl,
|
|
width,
|
|
height,
|
|
encoderOptions,
|
|
}: UseResizedImageProps): Accessor<string | undefined> => {
|
|
const [resizedImage, setResizedImage] = createSignal<string | undefined>(undefined);
|
|
|
|
createEffect(() => {
|
|
const sourceUrl = imageUrl();
|
|
|
|
if (sourceUrl == null) return;
|
|
|
|
const img = document.createElement('img');
|
|
img.addEventListener('load', () => {
|
|
const ratio = img.naturalWidth / img.naturalHeight;
|
|
const rw = height * ratio;
|
|
const rh = width / ratio;
|
|
const dw = Math.min(rw, width);
|
|
const dh = Math.min(rh, height);
|
|
|
|
const canvas = document.createElement('canvas');
|
|
canvas.height = dh;
|
|
canvas.width = dw;
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
|
|
if (ctx == null) throw new Error('failed to obtain context');
|
|
|
|
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, dw, dh);
|
|
|
|
const dataUrl = canvas.toDataURL('image/jpeg', encoderOptions);
|
|
|
|
setResizedImage(dataUrl);
|
|
});
|
|
img.src = sourceUrl;
|
|
});
|
|
|
|
return resizedImage;
|
|
};
|
|
|
|
export default useResizedImage;
|