Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Forked from brettbartylla/mouseDraw.js
Last active December 21, 2022 03:17
Show Gist options
  • Save JayGoldberg/a13c62f500979b4b8fc59ced7c313350 to your computer and use it in GitHub Desktop.
Save JayGoldberg/a13c62f500979b4b8fc59ced7c313350 to your computer and use it in GitHub Desktop.
This javascript allows a mouse to draw on an HTML5 Canvas
// Get the canvas and its context
var canvas = document.querySelector('#paint');
var ctx = canvas.getContext('2d');
// Get the parent element of the canvas and its computed style
var sketch = document.querySelector('.sketch');
var sketch_style = getComputedStyle(sketch);
// Set the canvas dimensions to match the parent element
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
// Mouse position
var mouse = {x: 0, y: 0};
// Last mouse position (for drawing)
var last_mouse = {x: 0, y: 0};
/* Mouse Capturing Work */
// Update the mouse position when the mouse moves
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
// Set the line style for drawing
ctx.lineWidth = 1;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#D3D3D3';
// Start drawing when the mouse moves over the canvas
canvas.addEventListener('mousemove', function(e) {
canvas.addEventListener('mousemove', onPaint, false);
}, false);
// Stop drawing when the mouse is released
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
// The function that does the actual drawing
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment