Skip to content
Advertisement

How to display binary image in react using canvas and useRefs

I have a mock RGBA image in the form [255, 0, 0, 255] and I want to display it on my webpage using 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} />;
};

I’m expecting a red pixel when I load this component in the main component, however, I can’t seem to load anything. Elements don’t even show up in the elements tab. Could someone guide me as to where I’m going wrong? Thanks!

Advertisement

Answer

According to the MDN, createImageData doesn’t copy the image data from the buffer.

imagedata An existing ImageData object from which to copy the width and height. The image itself is not copied.

You don’t need to create a separate imageData anyway;

ctx.putImageData(mockImage, 20, 20);

works just fine (moved to 20,20 since it’s easier to see).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement