console
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Painting</title>
<style>
canvas {
border: 1px solid black;
cursor: crosshair;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<div>
<button id="undoButton">Undo</button>
<button id="redoButton">Redo</button>
<button id="clearButton">Clear</button>
<button id="eraserButton">Eraser</button>
<button id="penButton">Pen</button>
<label for="penSize">Pen Size:</label>
<input type="range" id="penSize" min="1" max="50" value="10" />
<input type="color" id="colorPicker" value="#000000" />
</div>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.onmouseover
let isDrawing = false;
let isErasing = false;
let drawingArray = [];
let currentIndex = -1;
function startDrawing(event) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(event.clientX, event.clientY);
drawingArray.push(ctx.getImageData(0, 0, canvas.width, canvas.height));
currentIndex++;
}
function draw(event) {
if (isDrawing) {
ctx.lineTo(event.clientX, event.clientY);
ctx.lineJoin ="round";
ctx.lineCap = "round";
if (isErasing) {
ctx.globalCompositeOperation = "destination-out";
ctx.lineWidth = 30;
} else {
ctx.globalCompositeOperation = "source-over";
ctx.strokeStyle = document.getElementById("colorPicker").value;
ctx.lineWidth = document.getElementById("penSize").value;
}
ctx.stroke();
}
}
function endDrawing() {
isDrawing = false;
}
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", endDrawing);
function undoDrawing() {
if (currentIndex > 0) {
currentIndex--;
ctx.putImageData(drawingArray[currentIndex], 0, 0);
}
}
function redoDrawing() {
if (currentIndex < drawingArray.length - 1) {
currentIndex++;
ctx.putImageData(drawingArray[currentIndex], 0, 0);
}
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawingArray = [];
currentIndex = -1;
}
function activateEraser() {
isErasing = true;
}
function activatePen() {
isErasing = false;
}
const undoButton = document.getElementById("undoButton");
const redoButton = document.getElementById("redoButton");
const clearButton = document.getElementById("clearButton");
const eraserButton = document.getElementById("eraserButton");
const penButton = document.getElementById("penButton");
undoButton.addEventListener("click", undoDrawing);
redoButton.addEventListener("click", redoDrawing);
clearButton.addEventListener("click", clearCanvas);
eraserButton.addEventListener("click", activateEraser);
penButton.addEventListener("click", activatePen);
</script>
</body>
</html>