【问题标题】:How to display binary image in react using canvas and useRefs如何使用画布和 useRefs 在反应中显示二进制图像
【发布时间】:2021-08-24 20:20:40
【问题描述】:

我有一个 [255, 0, 0, 255] 形式的模拟 RGBA 图像,我想使用 react 在我的网页上显示它。

mockImageArray = [255, 0, 0, 255];
var mockImage = new ImageData(new Uint8ClampedArray(mockImageArray), 1, 1);

const Canvas = (props) => {
  const canvasRef = useRef(null);

  const draw = (ctx) => {
    var imageData = ctx.createImageData(mockImage);

    ctx.putImageData(imageData, 0, 0);
  };
  useEffect(() => {
    const canvas = canvasRef.current;
    canvas.width = 512;
    canvas.height = 256;
    const context = canvas.getContext("2d");

    draw(context);
  }, [draw]);

  return <canvas ref={canvasRef} {...props} />;
};

当我在主组件中加载这个组件时,我期待一个红色像素,但是,我似乎无法加载任何东西。元素甚至不会出现在元素选项卡中。有人可以指导我哪里出错了吗? 谢谢!

【问题讨论】:

  • [255, 0, 0, 255],我会更新代码以使其更清晰。谢谢!

标签: javascript reactjs html5-canvas


【解决方案1】:

根据 MDN,createImageData doesn't copy the image data from the buffer

imagedata 一个现有的 ImageData 对象,从中复制宽度和高度。图像本身不会被复制。

无论如何您都不需要创建单独的imageData

ctx.putImageData(mockImage, 20, 20);

工作得很好(移动到 20,20,因为它更容易看到)。

【讨论】:

  • 是的,这只是定位。谢谢!
猜你喜欢
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 2011-07-13
  • 2014-12-11
相关资源
最近更新 更多