【问题标题】:how to load Image and use it in canvas with gatsby SSR如何使用 gatsby SSR 加载图像并在画布中使用它
【发布时间】:2019-09-03 19:54:14
【问题描述】:

问题是我无法在我的 SSR 应用程序中使用不支持的类型创建图像:CSSImageValueHTMLImageElementSVGImageElementHTMLVideoElementHTMLCanvasElementImageBitmapOffscreenCanvas盖茨比。

我尝试canvas npm 包Canvas.Image 制作图像 HTMLImageElement 但它与 Image 构造函数消息也有相同的错误。

我的主要错误信息:

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)'

nodecanvas包代码和错误信息:

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

我使用react-konva 包来绘制画布,并在其中使用Image

【问题讨论】:

    标签: javascript reactjs canvas gatsby


    【解决方案1】:

    我终于找到了办法。 我创建了一个名为getImage 的函数,它将使用Promisecanvas loadImage 方法加载图像源:

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

    并在我的组件中轻松使用它:

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

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 2021-02-10
      • 2012-08-16
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2011-07-04
      • 2013-01-23
      相关资源
      最近更新 更多