I am trying to use a third-party javascript library in my react app (https://github.com/giventofly/pixelit). Since there was no npm package I downloaded the js file and imported it. It is supposed to take the image by its id and pixel it with the chosen colour palette. However, it is only able to read images on the index.html page and not that have been rendered in the JSX file. Is it because the library does not support react? or am I doing anything wrong?
Following is the working example provided:
<img src="assets/sky.jpg" id="pixelitimg" alt="" />
<canvas id="pixelitcanvas"></canvas>
<script>
const mypalette = [
[26, 28, 44],
// ...
];
const px = new pixelit({
from: document.getElementById("pixelitimg"),
palette: mypalette,
});
px.draw().pixelate().convertPalette();
</script>
This is how I use it:
import { pixelit } from "./pixelit";
const renderImage = () => {
const mypalette = [
[26, 28, 44],
// ...
];
const px = new pixelit(document.getElementById("pixelitimg"), mypalette);
px.draw().pixelate().convertPalette();
};
return (
<div>
<img src={twitterLogo} id="pixelitimg" alt="" />
<canvas id="pixelitcanvas"></canvas>
{renderimage()}
</div>
);
The react page doesn't show anything. However,when I add the image element and canva element in the index.html page, it works as intended.
I'm not sure if this is the cause of the error, but interacting directly with the DOM in React is not very good. You need to create a ref to the image.