Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Forked from zachdunn/drawing.js
Created December 21, 2022 03:15
Show Gist options
  • Save JayGoldberg/59841b2adb88ae62d006ac56c9a952b0 to your computer and use it in GitHub Desktop.
Save JayGoldberg/59841b2adb88ae62d006ac56c9a952b0 to your computer and use it in GitHub Desktop.
Canvas mouse drawing for a canvas #sketch plus button #clear.
(function(window){
// Define the Pen object, which handles drawing on the canvas
var Pen = function(context){
// Whether the user is currently drawing
var drawing;
// Reset the pen's drawing style
this.reset = function(){
context.beginPath();
context.lineCap = 'round';
context.lineWidth = 5;
context.strokeStyle = "#333333";
};
// Start drawing when the user clicks the mouse
this.mousedown = function(e){
drawing = true;
context.moveTo(e.x, e.y);
};
// Continue drawing as the user moves the mouse
this.mousemove = function(e){
if (drawing){
context.lineTo(e.x, e.y);
context.stroke();
context.moveTo(e.x, e.y);
}
};
// Stop drawing when the user releases the mouse
this.mouseup = function(e){
drawing = false;
context.lineTo(e.x, e.y);
context.stroke();
};
};
// Draw grid on canvas background
drawGrid = function(context) {
context.beginPath();
for (var x = 0.5; x < 500; x += 10) {
context.moveTo(x, 0);
context.lineTo(x, 500);
}
for (var y = 0.5; y < 500; y += 10) {
context.moveTo(0, y);
context.lineTo(500, y);
}
context.lineWidth = 1;
context.lineCap = "square";
context.strokeStyle = "#EFEFEF";
context.stroke();
};
// Once the page loads
window.onload = function(){
// Get the canvas element and its context
var canvas = document.getElementById('sketch');
var context = canvas.getContext('2d');
// Draw the grid on the canvas
drawGrid(context);
// Create a new Pen object and reset its drawing style
var pen = new Pen(context);
pen.reset();
// Set up the clear button to clear the canvas
var clearBtn = document.getElementById('clear');
clearBtn.addEventListener('click', function(e){
e.preventDefault();
context.clearRect(0,0,500,500);
drawGrid(context);
pen.reset();
});
// Set up the mouse event listeners for drawing
canvas.addEventListener('mousedown', pen.mousedown, false);
canvas.addEventListener('mousemove', pen.mousemove, false);
canvas.addEventListener('mouseup', pen.mouseup, false);
}
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment