I'm building an application around a 1000x1000 canvas, where you can select areas of the canvas by dragging the mouse around.
In order to remember the area selected from the user I save the coordinates in an array and I draw them with imageData:
const applySelectedPixelLayer = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
const imageData = ctx.createImageData(1, 1);
imageData.data[0] = 0; // R value
imageData.data[1] = 0; // G value
imageData.data[2] = 0; // B value
imageData.data[3] = 255; // A value
for (let i = 0; i < selectedCoordinates.length; i++) {
ctx.putImageData(
imageData,
selectedCoordinates[i][0],
selectedCoordinates[i][1]
);
}
}, [selectedCoordinates]);
Basically the user can click pixel on the canvas or drag the mouse to select a rectangle of pixels. When the user releases the mouse pointer, I add the coordinates selected to selectedCoordinates and then I call the applySelectedPixelLayer function to update the canvas.
The problem is that it's incredibly slow, it takes 20/30 seconds to see the result if a lot of pixels are selected.
Is there a more effective way to mark the selected pixel on a canvas?