Smart Board Learning

Code FunctionQuiz
Code LocationDrawing Pad
Code

Custom Drawing Pad

#drawing-pad {
border: 2px solid #000;
width: 100%;
max-width: 500px;
height: 300px;
background-color: #fff;
}

#drawing-pad canvas {
width: 100%;
height: 100%;
}

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
}

resizeCanvas();
window.addEventListener(“resize”, resizeCanvas);

// 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;
}

// Mouse and touch event listeners
canvas.addEventListener(“mousedown”, startDrawing);
canvas.addEventListener(“mousemove”, draw);
canvas.addEventListener(“mouseup”, stopDrawing);
canvas.addEventListener(“touchstart”, startDrawing, { passive: false });
canvas.addEventListener(“touchmove”, draw, { passive: false });
canvas.addEventListener(“touchend”, stopDrawing);
canvas.addEventListener(“mouseout”, stopDrawing);

// 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);
});
};

Date CreatedSeptember 2, 2024
Date UpdatedSeptember 2, 2024
Group 6 CopyCreated with Sketch.

More Information?

Fill out your details and we will get back to you as soon as possible.