Created
September 9, 2017 22:26
-
-
Save brettbartylla/3968faba2d8ba37edf270b22d07433cc to your computer and use it in GitHub Desktop.
This javascript allows a mouse to draw on an HTML5 Canvas. A working example of this is on my website.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//draw on home image | |
var canvas = document.querySelector('#paint'); | |
var ctx = canvas.getContext('2d'); | |
var sketch = document.querySelector('.sketch'); | |
var sketch_style = getComputedStyle(sketch); | |
canvas.width = parseInt(sketch_style.getPropertyValue('width')); | |
canvas.height = parseInt(sketch_style.getPropertyValue('height')); | |
var mouse = {x: 0, y: 0}; | |
var last_mouse = {x: 0, y: 0}; | |
/* Mouse Capturing Work */ | |
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 */ | |
ctx.lineWidth = 1; | |
ctx.lineJoin = 'round'; | |
ctx.lineCap = 'round'; | |
ctx.strokeStyle = '#D3D3D3'; | |
canvas.addEventListener('mousemove', function(e) { | |
canvas.addEventListener('mousemove', onPaint, false); | |
}, false); | |
canvas.addEventListener('mouseup', function() { | |
canvas.removeEventListener('mousemove', onPaint, false); | |
}, false); | |
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