Skip to content

Latest commit

 

History

History
349 lines (226 loc) · 12.8 KB

File metadata and controls

349 lines (226 loc) · 12.8 KB

p5.js

  • p5.js is built with JavaScript while Processing is built with Java.

  • p5.js first beta in August 2014

  • Libraries extend p5.js even further into domains including playing with sound and adding buttons, sliders, input boxes and webcam capture with HTML.

function setup() {
}

function draw() {
}

createCanvas(width, height); mouseIsPressed mouseX, mouseY

  • createCanvas() is a function that creates a drawing surface and attach it to the HTML page. Default size of the canvas is 100x100 pixels.
PI
QUARTER_PI
HALF_PI
TWO_PI
  • radians() function takes an angle in degrees and convert it into corresponding radian value.

  • Use angleMode(DEGREES) to use degrees instead of radians in the entire sketch.

  • strokeWeight(5) set the width of the drawn lines.

  • strokeJoin() function changes the way lines are joined and the strokeCap() function changes how lines are drawn at their begining and end.

  • Use fill() for fill color and stroke() for outlines.

  • Use noFill() to disable fill of a shape and noStroke() to disable stroke so that there is no outline.

  • beginShape() function signals the start of new shape. The vertex() function is used to define each pair of x and y coordinates for the shape. endShape() signal that the shape is finished.

  • The width and height of the canvas are stored in variables called width and height.

  • frameCount - frame count

  • The pmouseX and pmouseY variables store the position of the mouse at the previous frame.

  • The dist() function can be used to calculate the distance between two points.

  • easing: values to follow the mouse loosely, to lag behind to create a mouse fluid motion. Easing changes the number of steps it takes to move from one place to another.

let easing = 0.01;

let targetX = mouseX;
x += (targetX - x) * easing;
  • The mouseButton variable can: LEFT, CENTER or RIGHT

  • keyIsPressed to check if a key is pressed

  • Keys like Shift, Alt and arrow keys are coded. To check the code for these key use keyCode variable. The mose frequently used keyCode values are ALT, CONTROL, SHIFT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.

  • To isolate the effects of transformations so they don't affect later functions, use the push() and pop() functions. push() saves a copy of current coordinate system and then restore that system afte pop().

  • The preload() function runs once before the setup() function runs. You should generally load your images and other media in preload() in order to ensure they are fully loaded before the program starts.

var img;
function preload() {
    img = loadImage("test.jpg");
}

function setup() {
    createCanvas(480, 120);
}

function draw() {
    image(img, 0, 0);
}
  • preload() forces the program to wait until everything has loaded before moving on.

  • There are small number of fonts that most computers and devices have:

    • Arial
    • Courier
    • Courier New
    • Georgia
    • Helvetica
    • Palatino
    • Times New Roman
    • Trebuchet MS
    • Verdana
  • textFont() - set current font text() - draw letters to the screen textSize() - change text size

  • Webfont with open licenses GoogleFonts - https://fonts.google.com/ Open Font Library - https://fontlibrary.org/

  • To use a webfont, link it in the index.html page.

  • TrueType (.ttf) and OpenType (.otf) fonts

  • Vector drawing program

    • Inkscape
    • Illustrator
  • To create smooth motion, p5.js tries to run the code inside draw() at 60 frames each second.

  • If you call frameRate() with a parameter, it sets the frame rate to that value.

  • TrueType font uses outline fonts. Instead of being a collection of static pixels (a bitmap), a TrueType font is a set of mathematical descriptions (using quardratic Bezier curves) that define the outlines of each character or glyph.

  • TrueType fonts are like stencil: the font file doesn't contain a fixed size "a", but rather the instructions for drawing the perfect shape of an "a". This outline can then be scaled up or down to any size without losing quality.

  • serif - a short line at the end of the main strokes of a character

  • sans - Without; deprived or destitute of; rarely

  • The constrain() function limits a value to a specific range; ex: constrain(x, 0, width);

  • Every p5.js program counts the amount of time that has passed since it was started. Use millis() function to get this counter value.

  • A software object is a collection of related variables and functions. In the context of objects, a variable is called a property (or instance variable) and a function is called a method.

  • An object combines related data (properties) with related actions and behaviors (methods).

  • loadTable() function to load table data (csv/tsv) file

Nature of Code

  • A normal distribution (Gaussian distribution) is a nonuniform distribution of random numbers where the numbers cluster around an average value. A graph of this distribution is informally known as bell curve

  • In p5.js, randomGaussian() function returns random numbers with a normal distribution. randomGaussian() function takes two parameters, the mean and standard deviation.

  • oversampling: random() return previously returned value many times. To avoid such a problem is to take a very large step every so often, so that random numbers are generated around a specific value while periodically jumping far away to reduce the amount of oversampling. This variation of randomness is called Levy flight. (The longer the step, the less likely it is to be picked; the shorter the step, the more likely).

  • Perlin noise (Ken Perlin), produces a naturally ordered sequence of pseduorandom numbers, where each number in the sequence is quite close in value to the one before it.

  • p5.js library includes a function called noise() which generates smooth random values. noise() output range is fixed: it always returns a value from 0 to 1.

  • Euclidean vector also knows as the geometric vector. vector is an entity that has both magnitude and direction.

  • Instead of new p5.Vector(x, y);, call createVector(x, y);. The createVector() function is a helper function which takes care of details behind the scenes upon creation of the vector.

Eloquent JavaScript

  • Computers are dumb, pedantic (over-concerned with technical accuracy of minor details) beasts, programming is fundamentally tedious and frustrating.

  • JavaScript is built into every modern web browser

  • The best programs are those that manage to do something interesting while still being easy to understand.

  • arcane - Requiring secret or mysterious knowledge dispise - Look down on with disdain

  • To open a blank page: enter about:blank in the browser. To open a console window, press Ctrl+Shift+J

  • JavaScript is ridiculously liberal in what it allows.

  • Some database, such as MongoDB and CouchDB use JavaScript as their scripting and query language.

  • Node.js project provide an environment for programming JavaScript outside of the browser.

  • JavaScript uses fixed number of bits, 64 bits, to store a single number value.

  • There are three special values in JavaScript that are considered numbers:

    • Infinity
    • -Infinity
    • NaN
  • Strings can be marked with single quotes ('), double quoutes (") or backticks (`) called template literals.

  • Not all operators are symbols, some are written as words for example: typeof opeator.

  • There is only one value in JavaScript that is not equal to itself and that is NaN

  • There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

  • When you do not want any type conversions to happen, use === and !==

  • The ?? operator return the value on the right only if the one on the left is null or undefined, not if it is some other value that can be converted to false.

  • A fragment of code that produces a value is called an expression.

  • The keyword let allows us to create binding or variable.

  • The words var (pre-2015 JavaScript) and const can also be used to create bindings, in a similar fashion to let.

const func1 = function(x) { console.log(x); };

// this notation works even if func2 is defined belwo the code that uses it functon func2(y) { console.log(y); }

// Arrow function const roundTo = (n, step) => { ... }

const square1 = (x) => { return x * x; }; const square2 = x => x * x;


* JavaScript is extremely broad-minded about the number of arguments you can pass to a function. If you pass too many, the extra ones are ignored. If you pass too few, the missing parameters are assigned the value undefined.

* Almost all JavaScript values have properties. The exceptions are `null` and `undefined`.

* Two ways to access properties are with dot and with square brackets `value.x and value[x]`

* Every string has a `toUpperCase` property.

```JavaScript
let seq = [1, 2, 3];
seq.push(4);
seq.push(5);
console.log(seq);
console.log(seq.pop());
console.log(seq);
  • The push() method adds values to the end of an array. The pop() method remove the last value in the array and return it.

  • Values of the type object are arbitrary collections of properties.

  • The delete operator delete a property from the object delete obj.left

  • To check if a property exists in an object, use binary in operator.

  • Use Object.keys() to find what properties an object has.

  • Object.assign() copies all properties from one object to another.

  • Arrays have an includes() methods that checks whether a given value exists in the array.

  • A simpler way to write the classical for loop in moder JavaScript:

// classical JS
for(let i = 0; i < arr.length; ++i) {}
// modern JS
for(let entry of arr) {}
  • Array methods: unshift() - add element at the begining of array shift() - remove element from the beginning of the array indexOf() - search for a specific element, from start to end, in an array lastIndexOf() - search for a specific element, from end to start, in an array slice(start, end) - return an array that has only the elements between start and end

  • String methods: slice() - indexOf() - padStart(length, padChar) - split() - split a string on every occurrence of another string join() - join string repeat(count) - create new string containing multiple copies of original string

  • Rest Parameters a function can accept any number of arguments. To write such a function, put three dots before the function's last parameter

function sum(...numbers) {
    let s = 0;
    for(let num of numbers) {
        s += Number(num);
    }
    return s;
}
  • spread out array
let numbers = [2, 4, 6, 8];
console.log(max(...numbers));
  • Math.random() returns a new pseudorandom number between 0 (inclusive) and 1 (exclusive) every time it is called. For whole random number use Math.floor() with Math.random()

Math.floor(Math.random() * 100); random number between 0 - 99

  • Destructuring??

  • a?.b - a.b when a isn't null or undefined otherwise it evaluates to undefined

  • A popular serialization format is JavaScript Object Notation (JSON), widely used as a data storage and communication format on the web.

  • JavaScript functions - JSON.stringify and JSON.parse to convert data to and from this format.

  • Because of historical accident, typeof null also produces "object".

  • Abstractions give us the ability to talk about problems at a higher (or more abstract) level, without getting sidetracked by uninteresting details.

  • plain functions are a good way to build abstractions.

  • Higher-Order Functions: Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

  • There is a built-in array method, forEach that provides something like a for/of loop as a higher-order function.

  • Constructor Functions are pre-ES6 style

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.greet = function() {
    console.log(`Hi, I'm ${this.name}. I'm ${this.age} years old`);
}

const p = new Person("Aamir", 30);
p.greet();
  • Class Syntax [ES6 (2015)] added syntactic sugar over prototype system.
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log(`Hi, I'm ${this.name}. I'm ${this.age} years old`);
    }
}

const p = new Person("Aamir", 30);
p.greet();
  • forEach, filter map and reduce are standard array method.
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.forEach(e => console.log(e));
arr.filter(e => e % 2 != 0);  // [1, 3, 5, 7, 9]
arr.map(e => e * e);