【问题标题】:'react-native-canvas' return `Error: Image must be initialized with a Canvas instance`“react-native-canvas”返回“错误:必须使用 Canvas 实例初始化图像”
【发布时间】:2019-07-27 09:00:25
【问题描述】:

我正在使用react-native-canvas,想画一些图,但是当我尝试画图时出错了。

我阅读了一些问题on github,但它对我不起作用。

这是我的代码:

import Canvas, { Image as CanvasImage } from 'react-native-canvas';
import RNFS from 'react-native-fs';


    const _handleCanvas = (canvas) => {
        const image = new CanvasImage(canvas);
        canvas.width = 500;
        canvas.height = 500;
        image.src = `${RNFS.MainBundlePath}/${viewerData[0].path}`;
        console.log('image src: ', image.src);
        // the log here is ·undefined/../../images/3.jpg·
        const context = canvas.getContext('2d');
        image.addEventListener('load', () => {
            context.drawImage(image, 0, 0, 500, 500);
        });
    };

    return ( 
      <View>
            <Canvas ref={_handleCanvas} />
      </View>
)

我希望画一些东西,我该如何修复我的代码?

【问题讨论】:

    标签: javascript reactjs react-native canvas


    【解决方案1】:

    还要确保 ref 不为空:

    handleCanvas = (canvas) => {
        if (!(canvas instanceof Canvas)) {
          return;
        }
    
        const image = new CanvasImage(canvas);
        ...
    
    

    供参考:https://github.com/iddan/react-native-canvas/issues/133#issuecomment-581139760

    【讨论】:

      【解决方案2】:
      const image = new Image(canvas, height, width);
      

      创建构造函数的时候应该有height and width的参数,如上图,但是参数没有height and a width。 你能试试这个吗?

         const _handleCanvas = (canvas) => {
              width = 500;
              height = 500;
              const image = new CanvasImage(canvas, height, width);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 2019-08-16
        • 2020-05-12
        • 1970-01-01
        • 2022-08-18
        • 2017-04-22
        • 1970-01-01
        相关资源
        最近更新 更多