您可以将 nextjs 图像组件与 canvas 一起使用吗

Aid*_*ett 5 javascript reactjs next.js vercel

我正在创建一个图像滚动组件,例如 Apple Airpods Pro 网站。为此,我为此组件的每次迭代使用最多 750 个。我需要将图像绘制到画布上,目前,我正在使用标准 JS - new Image() 函数来生成 HTML 图像组件以绘制到画布上。我想合并下一个/图像缓存功能以确保它尽可能快地运行。这是可以实现的吗?

小智 0

Image包中的组件实际上next/image是一个普通img标签,这意味着您可以在context.drawImage(image, x, y)函数中使用它。

例子:

// Canvas reference
const canvasRef = useRef<HTMLCanvasElement>(null)

// Create imgRef reference
const imgRef = useRef<HTMLImageElement>(null)

// Effect when image and context are loaded
useEffect(() => {
    const canvas = canvasRef.current

    if (canvas === null)
        return

    const context = canvas.getContext('2d')

    if (context === null)
        return

    // Get the `img` from reference
    const image = imgRef.current

    if (image === null)
        return

    // Draw the image to the context
    context.drawImage(image, 0, 0)
}, [canvas, imgRef])
Run Code Online (Sandbox Code Playgroud)

最后Image向您的页面添加一个组件,如下所示:

<canvas
    ref={canvasRef}
    style={{
        border: 'solid 1px black',
    }}
></canvas>
// from `next/image`
<Image
    // attach a reference
    ref={imgRef}
    // source to the image
    src={'./myimage.png'}
    // Or import in a next.js fashion
    // import myImage from './myimage.png'
    // src={myImage}
    alt=""
    priority={true}
    // Hide it from displaying
    style={{
        display: 'none',
    }}
/>
Run Code Online (Sandbox Code Playgroud)