I am creating an app which is a "paint like".
So when the user click on the image it draws on it like this:
const drawHandler = () => {
const middle = brushSize / 2;
context.fillRect(
currentTransformedCursor.x - middle,
currentTransformedCursor.y - middle,
brushSize,
brushSize
);
};
When the user is moving its mouse over the image without clicking, so when mouseMove is trigger but mouseDown isn’t, I would like to show the user a preview of the rectangle that’ll be drawn if the user click.
I don’t want to fill the rectangle. I though of doing something like this:
const drawPreview = () => {
if (currentTransformedCursor) {
const middle = brushSize / 2;
context.strokeRect(
currentTransformedCursor.x - middle,
currentTransformedCursor.y - middle,
brushSize,
brushSize
);
}
};
The problem is the strokeRect is drawn and "save" to my canvas, resulting on my canvas being filled with ‘preview’. What I want is for the preview to only exists at specific place and instant, then if the cursor move, another preview would be created at the new place and the previous one would disappear.
I can’t clearReact because it clears any rectangle below the preview too and I need to keep that data.
I know I could create another context and delete the newest rectangle (the preview) on it but I was wondering about the existence of a feature that allow to show a preview of a rectangle without really drawing it to my canvas.
Thanks
2
Answers
I accepted the previous answer because it does work on simple cases.
However I have a lot of transformation on my canvas and the code wasn't working for me.
This is the code that does exactly what I need.
So these two lines clear the canvas: context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, canvas.width, canvas.height);
Then, I transform back with my current scaling and finally I draw the preview
You can place another canvas above the main one