How to create a sketch app in JavaScript using P5.JS

I have been learning P5.JS for a while now and though it would be nice to share the process and progress in form of a tutorial, which will motivate me to continue learning and give others access to it.

We will learn how to create a sketch app. I have kept it as basic as I can, this makes it easy to understand and quick to create.

To follow this tutorial you need to know basics of HTML and JavaScript.

Let’s start with What is P5.JS?

P5.JS is a javascript library based on Processing which was originally written in Java, for creating interactive applications, the reason to create such a framework was to make coding accessible for artists, educators, and beginners, over the years there have been many ports of this framework in different languages and P5 is one of them.

First, we need to get P5.JS(minified version), we are going with minified version because it contains the complete library in the smallest footprint possible.

Creating the bare-bone structure of the project

index.html lib/p5.min.js

We will then create run.js, this file will contain all the code we will be writing.

Our project should look something like this.

index.html lib/p5.min.js run.js

Time to write some HTML in the index.html file.

<meta charset="UTF-8">
<title>Sketch App</title>
<style>
    body {padding: 0; margin: 0;} canvas {vertical-align: top; border: 2px solid #000;}
</style>
<script type="text/javascript" src="lib/p5.min.js"></script>
<script type="text/javascript" src="run.js"></script>

As you can see above we have the p5.js library before run.js, since web browsers read code line by line it is important that the library is interpreted before run.js, otherwise all the code we have written will contain error because the web browser does not know what we are trying to do.

In P5.JS all the naming convention is followed based on what the function does and what it contains, this makes it easy to understand to a beginner.

It’s time to edit the run.js file.

The first function will be setup(). This will contain all the code that will initialize the program more like rules and instruction to follow.

function setup() { }

We will create the draw() function below setup(). The draw function will contain all the drawing tasks that will be running inside the canvas element that we will create in the next step.

function draw() { }

The code should look something like this.

function setup() { }

function draw() { }

Creating the canvas inside setup() using createCanvas() function.

The createCanvas() element takes two parameters, width, and height.

function setup() { 
    createCanvas(800, 800); // width, height 
}

If you open the web page you will see a white box with a size of 800 x 800 surrounded by a border of 2px.

You can change the background color using the background() function that takes one parameter.

function setup() { 
    createCanvas(800, 800); 
    background(85); // you can choose between 0 and 255. 
}

Let’s add some functionality to draw() which will make the magic happen.

function draw() { 
    if(mouseIsPressed) { 
    rect(mouseX, mouseY, 2,2) // X location, Y location, weight, height 
    } 
}

As you can see in the above code we have an if statement that has the mouseIsPressed function, this function checks if the mouse is pressed, using the if statement we are telling it to draw a rectangle with the rect() function on the X axis and Y while maintaining a width and height of 2px.

With the fill() function, we will make rect have its interior have white color.

function draw() { 
    if(mouseIsPressed) { 
        fill(255); / Choose between 0 to 255 rect(mouseX, mouseY, 5,5) // X location, Y location, weight, height 
        } 
}

We can remove the stroke around the rectangle by adding a noStroke() function, this will remove the stroke surrounding the rect we draw.

function draw() { if(mouseIsPressed) { 
        fill(255); // Choose between 0 to 255 noStroke(); 
        rect(mouseX, mouseY, 5,5) // X location, Y location, weight, height } 
}

The project is done. Good job!

The complete code in run.js should look like the snippet below.

function setup() { 
    createCanvas(800, 800); 
    background(85); 
} 
function draw() 
    { 
        if (mouseIsPressed) 
            { 
                fill(255); 
                noStroke(); 
                rect(mouseX, mouseY, 5, 5); 
    } 
}

This is how the final version should look.

You can download the completed source code of this project from GitHub.

Happy Coding and Happy New Year.

Open links in a new tab using jQuery

The most common way to open links in a new tab is to middle click the link in the web browser or right-click. To open a link in a new tab by default you need to add target="_blank" to the hyperlinks, but this would get annoying over time if you have to add this to every link in your source. You can add this simple jQuery snippet to your source to open every external link in a new tab of the web browser. If you don’t already have jQuery need a local copy of it or use Google’s hosted library CDN for jQuery.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>`

You need to load jQuery before this script loads or else this script won’t work.

$(document).ready(function(){
  $('a').each(function() {
    var a = new RegExp('/' + window.location.host + '/');
    if(!a.test(this.href)) {
      $(this).click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        window.open(this.href, '_blank');
      });
    }
  });
});

Node.js installation for Raspberry Pi…

Node.js is a brilliant platform for creating network applications. It is mainly known for its non-blocking I/O and event driven system. In simple terms, Node.js can easily handle a large number of requests while simultaneously consuming lesser server memory. These are the attributes one should be looking for in a low power server like, you guessed it, Raspberry Pi. Here, you’ll learn how to setup Node.js for Raspberry Pi.

Node.js

ON

Raspberry Pi

Why use Node.js?

Node.js comes with a built in HTTP server library. This means it doesn’t require the help of any external piece of software to act as a web-server. Using Node.js alone one can have greater control of the web-server parameters.

Of course, all we care about it tinkering. Cool new web applications require Node.js to function and we like our Raspberry Pi not being a source of heat all the time. Of course, you could check the Wikipedia entry as well as their very own site.

Installing Node.js on Raspberry Pi

1. Download the Node.js package for ARM

As you must be aware, the Raspberry Pi sports an ARM11 chip. So, the package optimised for ARM will have to be downloaded. It can be done by entering the following command into the terminal.

wget http://node-arm.herokuapp.com/node_latest_armhf.deb

2. Install the package

Once the download is complete, it needs to be installed and can be done using the following command.

sudo dpkg -i node_latest_armhf.deb

And that’s it! Quick, wasn’t it?

By its end, we will have NodeJS and NPM (Node Package Manager) installed on your Raspberry Pi.

Testing the installation

The process is pretty foolproof but it wouldn’t hurt to test the installation with a simple server script.

1. Write the server script

Below, we have written a script that displays “Hello World!” to the client.

var http = require('http');
http.createServer(function (request,response) {
 response.writeHead(200, {'Content-Type': 'text/plain'});
 response.end('Hello World!\n');
}).listen(8000)
console.log("Web Server running at http://127.0.0.1:8000")

Update: There’s a chance the code might not appear in with proper line-breaks on your PC. So, here below we’ve enlisted the above code in its right syntax:

 

#### Save the script in a file

Save the script in a .js javascript file. Something like greetings.js would be a good idea if you’re not feeling particularly creative.

2. Run the script

Use the node program from the command line to execute the server. Something like so.

node greetings.js

You’ll receive an output like this.

Hello World!

If you’d like you could visit http://127.0.0.1:8000 and be greeted “Hello World!”.

And that is that!

Stay tuned for more on Raspberry Pi, Node.js and all of the web-apps based on it. Do leave us comments if you’d like us to do anything for you…