Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Canvas Line Drawing
var ctx = document.getElementById('draw-canvas').getContext('2d'),
penX = [],
penY = [],
saveStates = [],
drawOn = false,
trackingInitialized = false,
canvasWidth, canvasHeight;
ctx.strokeStyle = '#000';
ctx.lineJoin = 'round';
ctx.lineWidth = 3;
//listener for tracking our pen and redrawing
function moveUpdate(e){
if(drawOn === true){
//keep saving the new x and y values of the mouse
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.putImageData(saveStates[saveStates.length - 1], 0, 0);
for(var i = 1; i < penX.length; i++){
ctx.moveTo(penX[i - 1], penY[i - 1]);
ctx.lineTo(penX[i], penY[i]);
//again, we only want to draw when the user is holding the mouse button down, so here's two additional listeners to handle that
function downUpdate(e){
if(trackingInitialized === false){
saveStates.push(ctx.getImageData(0, 0, canvasWidth, canvasHeight));
trackingInitialized = true;
drawOn = true;
//when the user lets go, we need to update our booleans
function letGoUpdate(e){
saveStates.push(ctx.getImageData(0, 0, canvasWidth, canvasHeight));
drawOn = false;
penX.splice(0, penX.length);
penY.splice(0, penY.length);
function clearCanvas(){
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
saveStates.splice(0, saveStates.length);
trackingInitialized = false;
function convertToPNG(){
//get our image data, we will use a data url to create a image element
var doc = document,
imageContainer = doc.getElementById('image-container'),
dataUrl = doc.getElementById('draw-canvas').toDataURL(),
image = doc.createElement('img');
$('#image-container').empty().append('<p>Right Click > Save as</p>');
image.src = dataUrl;
function clearImage(){
function init(){
var doc = document,
drawCanvas = doc.getElementById('draw-canvas'),
clearCanvasButton = doc.getElementById('clear-canvas-button'),
convertCanvasButton = doc.getElementById('convert-canvas-button'),
clearImageButton = doc.getElementById('clear-image-button');
canvasWidth = drawCanvas.width;
canvasHeight = drawCanvas.height;
//draw handlers
drawCanvas.addEventListener('mousemove', moveUpdate, false);
drawCanvas.addEventListener('mousedown', downUpdate, false);
drawCanvas.addEventListener('mouseup', letGoUpdate, false);
//clear and conversion handlers
clearCanvasButton.addEventListener('click', clearCanvas, false);
convertCanvasButton.addEventListener('click', convertToPNG, false);
clearImageButton.addEventListener('click', clearImage, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.