Drawing with Canvas

How to make a simple canvas drawing app

by tararoys

HTML

<canvas id="sketchpad" width="300" height="300">

CSS

body{
 background-color: black;
}

canvas{
 background-color: white;
}

JavaScript

var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
						
		// create a drawer which tracks touch movements
		var drawer = {
			isDrawing: false,
			mousedown: function(coors){
				context.beginPath();
				context.moveTo(coors.x, coors.y);
				this.isDrawing = true;
			},
			mousemove: function(coors){
				if (this.isDrawing) {
			        context.lineTo(coors.x, coors.y);
			        context.stroke();
				}
			},
			mouseup: function(coors){
				if (this.isDrawing) {
			        this.mousemove(coors);
			        this.isDrawing = false;
				}
			}
		};
		// create a function to pass touch events and coordinates to drawer
function draw(event){
			// get the touch coordinates
	var coors = {
				x:event.pageX,
y: event.pageY
			};
// pass the coordinates to the appropriate handler
			drawer[event.type](coors);
		}
		
// attach the touchstart, touchmove, touchend event listeners. 
 canvas.addEventListener('mousedown',draw, false);
 canvas.addEventListener('mousemove',draw, false);
 canvas.addEventListener('mouseup',draw, false);