简体   繁体   中英

how to load Image and use it in canvas with gatsby SSR

The problem is I could not create image with none of the supported types : CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas in my SSR application with gatsby .

I tried canvas npm package Canvas.Image to make image HTMLImageElement but it has same error with Image constructor message too.

my main error message :

Context.js:225 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

node canvas package code and error message :

import { Image as CanvasImage } from 'canvas';

const image = new CanvasImage();
image.src = avatars[avatar];

console.log(image);
TypeError: canvas__WEBPACK_IMPORTED_MODULE_3__.Image is not a constructor

I use react-konva package to draw canvas and Image in it.

Finally I got the way to do this. I create a function named getImage which gonna load image source from canvas loadImage method with a Promise :

import { loadImage } from 'canvas';

export async function getImage(src, cb) {
  return loadImage(src)
    .then((image) => image)
    .catch(err => console.log(err));
};

And use it in my component with ease :

let [imageSource, setImageSource] = useState();
useEffect(() => {
  getImage(ladderSvg)
    .then((image) => setImageSource(image))
} , []);

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