Simple Drawing Application

Authored by John Kuiphoff


We are going to spend some time building a drawing application using p5.js. We will start off by building something very simple. Then, you will be asked to add additional functionality using some of the concepts (buttons, sliders, variables, etc).

Super Simple Drawing App

To begin, open up the 'sketch.js' file inside of the empty-example folder using Sublime Text, Brackets or the dedicated P5js editor and add the following code:

function setup() {
 	createCanvas(400, 400);
}

function draw()
{
	// do nothing
}

function mouseDragged() 
{ 
	strokeWeight(10);
	line(mouseX, mouseY, pmouseX, pmouseY);
}

In this sketch, we are drawing a line from the current mouse position to the previous mouse position when the mouse is dragged. The mouseDragged() event handler is called once every time the mouse moves and a mouse button is pressed. If you look at the documentation, you'll see that you can use the touchMoved() function if using a mobile device.

Adding a simple color option

Now we are going to add a variable that will allow us to change the color that we are applying to the canvas. In this case, the color can be changed by pressing a key on the keyboard.

var c;

function setup() {
 	createCanvas(600, 600);
 	c = color(0);
}

function draw()
{
	// display instructions
	noStroke();
	fill(200);
	rect(0, 0, width, 25);
	fill(0);
	text("Press the 'R' key on your keyboard to change the color", 10, 15);
}

function mouseDragged() 
{ 
	strokeWeight(10);
	stroke(c);
	line(mouseX, mouseY, pmouseX, pmouseY);
}

function keyPressed()
{
	if(key == 'r' || key == 'R')
	{
		c = color(255, 0, 0);
	}
}

Of course, you can improve this by using buttons or sliders instead.

Additional features

There are a number of additional features that you could using what we've learned so far. Some of these might include:

comments powered by Disqus