Javascript

chapter 2

Javascript

Javascript is the tool to work with browser and used also for interactive programming purposes.

Getting started with Javascript

Learn about javascript here and also here

Lets get started with p5.js example such as pointillism

p5.js is a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.

for more info see here

Create an html file i.e index.html and copy paste the below code:

<html>
<head>
  <meta charset="UTF-8">
  <script language="javascript" type="text/javascript" src="libraries/p5.js"></script>
  <!-- uncomment lines below to include extra p5 libraries -->
  <script language="javascript" src="libraries/p5.dom.js"></script>
  <script language="javascript" src="libraries/p5.sound.js"></script>
  <script language="javascript" type="text/javascript" src="sketch.js"></script>
  <!-- this line removes any default padding and style. you might only need one of these values set. -->
  <style> body {padding: 0; margin: 0;} </style>
</head>

<body>
</body>
</html>

then create a javascript file called pointillism.js and insert the below code:

//pointillism example p5
var img;
var smallPoint, largePoint;

function preload() {
    img = loadImage("assets/myPhoto.jpg");//use low res (72) photo
}

function setup() {
    createCanvas(720, 400);
    smallPoint = 4;
    largePoint = 40;
    imageMode(CENTER);
    noStroke();
    background(255);
    img.loadPixels();
}

function draw() {
    var pointillize = map(mouseX, 0, width, smallPoint, largePoint);
    var x = floor(random(img.width));
    var y = floor(random(img.height));
    var pix = img.get(x, y);
    fill(pix, 128);
    ellipse(x, y, pointillize, pointillize);
}

You need also to create a floder named 'assets' inside your Js project with a myphoto.jpg (you can choose the photo you desired and named it myphoto.jpg or just go and change the name inside the pointillism.js)

Change the name of the .jpg file: pointillism.js

function preload() {
    img = loadImage("assets/myPhoto.jpg");//use low res (72) photo
}

Run

To see the results in your browser just open the insex.html file with the browser.

Alternative, you can run a server locally. To do this open terminal and type the below command:

Run a local server with python

Open terminal and type the below command

python -m http.server

Another way to