|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useLayoutEffect, useState } from 'react' |
| 4 | +import clsx from 'clsx' |
| 5 | + |
| 6 | +import { AutoResizeHeight } from '~/components/widgets/shared/AutoResizeHeight' |
| 7 | + |
| 8 | +function cropImageTo16by9(src: string): Promise<string> { |
| 9 | + return new Promise((resolve, reject) => { |
| 10 | + const img = new Image() |
| 11 | + img.crossOrigin = 'anonymous' |
| 12 | + img.onload = () => { |
| 13 | + const canvas = document.createElement('canvas') |
| 14 | + const ctx = canvas.getContext('2d')! |
| 15 | + |
| 16 | + const aspectRatio = 838 / 224 |
| 17 | + let cropWidth = img.width |
| 18 | + let cropHeight = cropWidth / aspectRatio |
| 19 | + |
| 20 | + if (cropHeight > img.height) { |
| 21 | + cropHeight = img.height |
| 22 | + cropWidth = cropHeight * aspectRatio |
| 23 | + } |
| 24 | + |
| 25 | + const left = (img.width - cropWidth) / 2 |
| 26 | + const top = (img.height - cropHeight) / 2 |
| 27 | + |
| 28 | + // 设置 canvas 尺寸和绘制裁剪的图像 |
| 29 | + canvas.width = cropWidth |
| 30 | + canvas.height = cropHeight |
| 31 | + ctx.drawImage( |
| 32 | + img, |
| 33 | + left, |
| 34 | + top, |
| 35 | + cropWidth, |
| 36 | + cropHeight, |
| 37 | + 0, |
| 38 | + 0, |
| 39 | + cropWidth, |
| 40 | + cropHeight, |
| 41 | + ) |
| 42 | + |
| 43 | + // 转换 canvas 内容为 blob URL |
| 44 | + canvas.toBlob((blob) => { |
| 45 | + if (blob) { |
| 46 | + const url = URL.createObjectURL(blob) |
| 47 | + resolve(url) |
| 48 | + } else { |
| 49 | + reject('Blob conversion failed') |
| 50 | + } |
| 51 | + }, 'image/jpeg') |
| 52 | + } |
| 53 | + img.onerror = reject |
| 54 | + |
| 55 | + // 设置图像源以开始加载 |
| 56 | + img.src = src |
| 57 | + }) |
| 58 | +} |
| 59 | + |
| 60 | +export const NoteHeadCover = ({ image }: { image: string }) => { |
| 61 | + const [imageBlob, setImageBlob] = useState<string | null>(null) |
| 62 | + useLayoutEffect(() => { |
| 63 | + let isMounted = true |
| 64 | + cropImageTo16by9(image).then((b) => { |
| 65 | + if (!isMounted) return |
| 66 | + setImageBlob(b) |
| 67 | + }) |
| 68 | + return () => { |
| 69 | + isMounted = false |
| 70 | + } |
| 71 | + }, [image]) |
| 72 | + return ( |
| 73 | + <> |
| 74 | + <AutoResizeHeight> |
| 75 | + <div |
| 76 | + className={clsx( |
| 77 | + 'z-1 absolute left-0 right-0 top-0', |
| 78 | + imageBlob ? 'h-[224px]' : '0', |
| 79 | + )} |
| 80 | + > |
| 81 | + <div |
| 82 | + style={{ |
| 83 | + backgroundImage: `url(${imageBlob})`, |
| 84 | + }} |
| 85 | + className="cover-mask-b h-full w-full bg-cover bg-center bg-no-repeat" |
| 86 | + /> |
| 87 | + </div> |
| 88 | + </AutoResizeHeight> |
| 89 | + |
| 90 | + <AutoResizeHeight> |
| 91 | + <div className={imageBlob ? 'h-[120px]' : 'h-0'} /> |
| 92 | + </AutoResizeHeight> |
| 93 | + </> |
| 94 | + ) |
| 95 | +} |
0 commit comments