Created
May 24, 2013 03:11
-
-
Save zachdunn/5641060 to your computer and use it in GitHub Desktop.
Canvas mouse drawing for a canvas #sketch plus button #clear.
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
(function(window){ | |
var Pen = function(context){ | |
var drawing; | |
this.reset = function(){ | |
context.beginPath(); | |
context.lineCap = 'round'; | |
context.lineWidth = 5; | |
context.strokeStyle = "#333333"; | |
}; | |
this.mousedown = function(e){ | |
drawing = true; | |
context.moveTo(e.x, e.y); | |
}; | |
this.mousemove = function(e){ | |
if (drawing){ | |
context.lineTo(e.x, e.y); | |
context.stroke(); | |
context.moveTo(e.x, e.y); | |
} | |
}; | |
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(){ | |
var canvas = document.getElementById('sketch'); | |
var context = canvas.getContext('2d'); | |
drawGrid(context); | |
var pen = new Pen(context); | |
pen.reset(); | |
// Allow canvas to be re-rendered | |
var clearBtn = document.getElementById('clear'); | |
clearBtn.addEventListener('click', function(e){ | |
e.preventDefault(); | |
context.clearRect(0,0,500,500); | |
drawGrid(context); | |
pen.reset(); | |
}); | |
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