简体   繁体   中英

Failed to Execute DrawImage in Next.js

I'm new to Next.js. I'm trying to load image in html canvas and do some work on it.

When I try to draw on canvas I'm getting this error

Unhandled Runtime Error
TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.

This is my code

import Image from "next/image";

function tileImage() {
  return <Image src="/tiles.png" alt="tiles" />;
}
           
const draw = (ctx) => {
    for (var c = 0; c < map.cols; c++) {
      for (var r = 0; r < map.rows; r++) {
        var tile = map.getTile(c, r);
        if (tile !== 0) {
          // 0 => empty tile
          ctx.drawImage(
            tileImage, // image
            (tile - 1) * map.tsize, // source x
            0, // source y
            map.tsize, // source width
            map.tsize, // source height
            c * map.tsize, // target x
            r * map.tsize, // target y
            map.tsize, // target width
            map.tsize // target height
          );
        }
      }
    }
  };

  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Canvas draw={draw} />
      </main>
    </div>
  );
}

Any Help will be appreciated. Thanks in advance.

OK, another idea: You passing function not img. Try this:

const imgRef=useRef();

...
ctx.drawImage(
            imgRef.current, // image
            (tile - 1) * map.tsize, // source x

...
 <div className={styles.container}>
      <main className={styles.main}>
        <Canvas draw={draw} />
        <img src="/tiles.png" alt="tiles" ref={imgRef}/>
      </main>
 </div>
...

I faced the same problem with Next.js, and I solved it easily by writing window like this:-

...
const img = new window.Image();
img.src = '...';
img.onload = () => {
    ctx.drawImage(img, 0, 0, myWidth, myHeight);
};
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM