I am creating a paint application using canvas. If I want to draw, then it works, but the undo and clear buttons are not working fine, so if I click those buttons, then it throws an error saying “ctx.FillRect is not a function”, so how do I make those buttons work fine in React so that all that functionality will work fine? Codes are given below.
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
let restore_array = [];
let index = -1;
useEffect(() => {
const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth - 60;
canvas.height = 300;
const ctx = canvas.getContext("2d");
let start_back_ground_color = "red";
ctx.fillStyle = start_back_ground_color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
let draw_color = "black";
let draw_width = 5;
let is_drawing = false;
canvas.addEventListener("touchstart", start, false);
canvas.addEventListener("touchmove", draw, false);
canvas.addEventListener("mousedown", start, false);
canvas.addEventListener("mousemove", draw, false);
canvas.addEventListener("touchend", stop, false);
canvas.addEventListener("mouseup", stop, false);
canvas.addEventListener("mouseout", stop, false);
function start(e) {
is_drawing = true;
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
e.preventDefault();
}
function draw(e) {
if (is_drawing) {
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.strokeStyle = draw_color;
ctx.lineWidth = draw_width;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.stroke();
}
}
function stop(e) {
if (is_drawing) {
ctx.stroke();
ctx.closePath();
is_drawing = false;
}
e.preventDefault();
if (e.type !== "mousetype") {
restore_array.push(ctx.getImageData(0, 0, canvas.width, canvas.height));
index += 1;
}
}
});
const clearCanvas = () => {
const ctx = document.createElement("canvas").getContext("2d");
const canvas = document.getElementById("canvas");
ctx.fillStyle = "red";
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.FillRect(0, 0, canvas.width, canvas.height);
restore_array = [];
index = -1;
};
const undoCanvas = () => {
const ctx = document.createElement("canvas").getContext("2d");
if (index <= 0) {
clearCanvas();
} else {
index -= 1;
restore_array.pop();
ctx.putImageData(restore_array[index], 0, 0);
}
};
return (
<div className="App">
<div className="field">
<canvas id="canvas"></canvas>
<div className="tools">
<button onClick={undoCanvas} className="button">
Undo
</button>
<button onClick={clearCanvas} className="button">
clear
</button>
</div>
</div>
</div>
);
}
