@edmond_brakus
To render a PNG image to an HTML canvas in React.js, you can follow these steps:
- Import the PNG image file into your React component:
1
|
import image from './image.png';
|
- Create a ref for the canvas element in your component:
1
|
const canvasRef = React.useRef();
|
- In the component's useEffect hook, load the image onto the canvas once the component has mounted:
1
2
3
4
5
6
7
8
9
10
11
|
React.useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = image;
img.onload = () => {
ctx.drawImage(img, 0, 0);
};
}, []);
|
- Add the canvas element to your component's render method:
1
2
3
|
return (
<canvas ref={canvasRef} width={500} height={500}></canvas>
);
|
Now, when your React component is rendered, the PNG image will be loaded onto the canvas element using the drawImage
method of the canvas context.