Skip to content

Commit

Permalink
refactor: useImageRender hook
Browse files Browse the repository at this point in the history
  • Loading branch information
tjmaynes committed Feb 23, 2024
1 parent a980fe8 commit 376a2e3
Showing 1 changed file with 22 additions and 24 deletions.
46 changes: 22 additions & 24 deletions src/app/_hooks/useImageRender.tsx
Expand Up @@ -24,33 +24,31 @@ export const useImageRender = (
const canvas = canvasRef.current
if (!canvas) return

const context = canvasRef.current?.getContext('2d', {
willReadFrequently: true,
})

const context = canvas.getContext('2d', { willReadFrequently: true })
if (!context) return

createImageBitmap(imageBlob).then((imageBitmap) => {
const options = {
imageHeight: imageBitmap.height,
imageWidth: imageBitmap.width,
maxHeight,
maxWidth,
}

const { width, height } = resizeImage(options)

context.canvas.width = width
context.canvas.height = height

context.drawImage(imageBitmap, 0, 0, width, height)

setImageRenderState({
isLoading: false,
imageData: context.getImageData(0, 0, width, height),
createImageBitmap(imageBlob)
.then((imageBitmap) => {
const { width, height } = resizeImage({
imageHeight: imageBitmap.height,
imageWidth: imageBitmap.width,
maxHeight,
maxWidth,
})

context.canvas.width = width
context.canvas.height = height
context.drawImage(imageBitmap, 0, 0, width, height)

setImageRenderState({
isLoading: false,
imageData: context.getImageData(0, 0, width, height),
})
})
.catch((error) => {
console.error('Error loading image:', error)
})
})
}, [canvasRef, maxWidth, maxHeight, imageBlob])
}, [maxWidth, maxHeight, imageBlob])

return { imageRenderState, canvasRef }
}

0 comments on commit 376a2e3

Please sign in to comment.