如何在画布中添加项目文件夹的本地图像?

问题描述

我试图在画布中打开项目文件夹图像,而不将其上传文件输入中。但它没有显示在那里,我正在使用 react-konva 添加图像。

这是我尝试上传图片代码

      const img = new window.Image();
      img.src = require('../../../assets/images/71.png');
      img.onload = function () {
        const img_width = this.width;
        console.log('the image',require('../../../assets/images/71.png'));
        const img_height = this.height;

        const max = img_width > img_height ? 100 : 100;
        const ratio = (img_width > img_height ? (img_width / max) : (img_height / max))
        setoriginalDim({ width: img_width,height: img_height });
        setDimensions({ width: img_width/ratio,height: img_height/ratio });
        const theImg = new Konva.Image({
          image: this,x: 0,y: 0,width: img_width/ratio,height: img_height/ratio,name: 'background_image',draggable: true
        });

        if (layerRef.current != null) {
          console.log('image',theImg);
          layerRef.current.add(theImg);
          layerRef.current.draw();
        }
      };

我的反应组件是这样的:

<Stage
              width={dimensions.width}
              height={dimensions.height}
              onMouseDown={handleStageMouseDown}
              style={{ backgroundColor: '#fff',BoxShadow: '0 0 6px 0 #666' }}
              ref={stageRef}
              id="certificate_canvas"
            >
              <Layer
                ref={layerRef}
              />
</Stage>

onload 部分没有执行,图像也没有加载到画布中。如何在不上传的情况下添加项目文件夹图像

解决方法

代替这个

img.src = require('../../../assets/images/71.png');

使用

img.src = '../../../assets/images/71.png';

你不需要 require 函数