Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Browser Image within Canvas in React

Tags:

reactjs

canvas

I am trying to simply load a local image and draw it to the browser within a canvas element within a react functional component but am struggling:

import { useEffect, useRef } from 'react';

export default function Canvas({ width, height }) {

    const myCanvas = useRef();

    useEffect(() => {
        const context = myCanvas.current.getContext('2d');
        const image = new Image();
        image.src = '/home/ben/consensys/eth-og/src/static/preview.jpg';
        context.drawImage(image, 0, 0, 100, 100);
    })

    return (
        <canvas
            ref={myCanvas}
            width={width}
            height={height}
        />
    )
}

Then in App.js:

import Canvas from './Canvas';

function App() {

  return (
    <Web3ReactProvider getLibrary={getLibrary}>
      <div className="App">
        <Canvas height={500} width={500} />
      </div>
  );
}

export default App;

My browser is displaying the canvas element, but there is no image on it, just an empty placeholder. Any ideas?

like image 479
Reno Avatar asked Oct 24 '25 04:10

Reno


1 Answers

Base on shared code, the issue is on image load. You are trying to draw the image before it loaded, that's why the canvas displays an empty block...

You can resolve this issue by using image.onload, for example:

  const myCanvas = useRef();

  useEffect(() => {
    const context = myCanvas.current.getContext("2d");
    const image = new Image();
    image.src =
      "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Picture_icon_BLACK.svg/1200px-Picture_icon_BLACK.svg.png";
    image.onload = () => {
      context.drawImage(image, 0, 0, 500, 500);
    };
  }, []);

  return <canvas ref={myCanvas} width={500} height={500} />;

And this is demo url (copied from your code)

like image 104
Anees Hikmat Abu Hmiad Avatar answered Oct 26 '25 18:10

Anees Hikmat Abu Hmiad