【问题标题】:How to add local image of project folder in canvas?如何在画布中添加项目文件夹的本地图像?
【发布时间】:2023-03-16 16:59:01
【问题描述】:

我正在尝试在画布中打开项目文件夹图像而不将其上传到文件输入中。但它没有显示在那里,我正在使用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 部分未执行,图像也未加载到画布中。如何在不上传的情况下添加项目文件夹图片

【问题讨论】:

  • 你在console.log('the image', require('../../../assets/images/71.png')); 中有什么记录图像 URL 吗?

标签: reactjs image canvas konvajs


【解决方案1】:

而不是这个

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

使用

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

你不需要 require 函数

【讨论】:

  • 即使在那之后它也没有调用 onload 回调
  • 你能贴一张你的控制台的照片吗??
  • 日志语句不起作用,代码没有到达那里
  • 它没有显示任何错误?设置后尝试记录图像的 src 我也建议您使用 const img = document.createElement("image");不是 const img = new window.Image();
  • src 正在打印,但 img 没有显示,这两种方式都不适用于外部图像 URL 图像即将到来但对于本地图像它不是
猜你喜欢
  • 2017-05-02
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 2011-01-25
  • 2023-03-23
  • 2018-08-18
  • 2012-05-10
  • 1970-01-01
相关资源
最近更新 更多