window.onload = function() {
var canvas = document.querySelector(“#drawing-pad canvas”);
var ctx = canvas.getContext(“2d”);
var drawing = false;
// Set up canvas size and scaling
function resizeCanvas() {
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
ctx.scale(ratio, ratio);
ctx.lineWidth = 2;
ctx.lineCap = “round”;
ctx.strokeStyle = “#000”; // Set the pen color to black
}
// Get position for both mouse and touch events
function getPosition(e) {
var rect = canvas.getBoundingClientRect();
return {
x: (e.touches ? e.touches[0].clientX : e.clientX) – rect.left,
y: (e.touches ? e.touches[0].clientY : e.clientY) – rect.top
};
}
// Start drawing
function startDrawing(e) {
drawing = true;
ctx.beginPath();
ctx.moveTo(getPosition(e).x, getPosition(e).y);
e.preventDefault(); // Prevent any scrolling or zooming
}
// Draw on the canvas
function draw(e) {
if (!drawing) return;
var pos = getPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
e.preventDefault();
}
// Stop drawing
function stopDrawing() {
drawing = false;
}
// Prevent scrolling and zooming while interacting with the canvas
canvas.addEventListener(“touchmove”, function(e) {
e.preventDefault();
}, { passive: false });
// Clear the canvas without refreshing the page
document.getElementById(“clear-button”).addEventListener(“click”, function(e) {
e.preventDefault(); // Prevent the default behavior (which might be submitting a form)
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
};