A set of utilities and additional features for my creative coding class aiming to help students while introducing the algorithmic thinking.

Overview

p5.utils

A set of utilities and additional features for my creative coding class aiming to help students while introducing the algorithmic thinking.

The list of utilities in p5.Utils repository. Click on thumbnails to access examples on p5JS editor;

1_pixelRuler 2_debugView 3_getTimeStamp
4_saveCanvas 5_arrayResize 6_fxShadow
7_GradientFill 8_RadialGradientFill 9_Countdown

How to use p5.Utils library?


Option 1 (Quick Start via P5JS Online Editor)

  1. Navigate to p5JS examples collection.
  2. Click on p5.utils.template.
  3. Hit CMD+s (or File->Save). This will create a copy of required files in your P5JS account. Whenever you need to access p5.utils you can follow the same steps.

Option 2 (If you are using local text editor like VSCode for development)

  1. Download the final minified js version from "Releases" page.

  2. Upload p5.utils.min.js to your project folder in p5 editor.

  3. Include the p5.utils.min.js in the index.html document before p5.js libs as follows;

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
    <script src="libraries/p5.utils.min.js"></script>
    
  4. Declare and initialize the lib before the setup() prefably as follows;

    var utils = new p5.Utils();
    
  5. Now you can call any methods defined in p5.utils library using dot notation as follows in setup() or any other custom methods in your code;

    utils.enablerRuler(); 
    

Option 3 (Import the lib. using CDN service)

  1. Include CDN source to you ìndex.html.
<script src="https://cdn.jsdelivr.net/gh/alptugan/p5.utils@latest/src/p5.utils.min.js"></script>
  1. Repeat the above steps 4 and 5.

Reference


p5.Utils library

p5.Utils extends p5 with several functionalities including cheaper drawingcontext effects, pixel ruler (useful for new commers), array operations, file naming, dom based debug window to avoid rendering text in p5JS.

Functions

debug(_itemName)

Create Debug Div cause p5 font is expensive.

getTimeStamp([_date])String

Timestamp function useful for file naming to avoid overwrite issues.

saveCanvas([_prefix], [_suffix])

Utilizes p5JS saveCanvas function to make it easier file saving process by combining the function with getTimeStamp() method.

arrayResize(_arr, _newSize, [_defaultValue])Array.<Number> | Array.<String> | Array.<Boolean>

Resizes an array and returns it. Similar to vectors resize in C++.

beginShadow(_color, _shadowBlur, _shadowOffsetX, _shadowOffsetY)

Creates shadow effect usign drawing context. Must be used with endShadow method. See examples for how to use it.

endShadow()

Stops shadow effect for the following graphics on the canvas. For example usage beginShadow page.

beginLinearGradient(_colorsArr, _startX, _startY, _endX, _endY, _colorsRatio)

Default Context 2D Gradient fill style. Must be used with endLinearGradient method. See examples for how to use it.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient

endLinearGradient()

Stop Gradient fill for the following graphics. Must be used with beginLinearGradient method. See examples for how to use it.

text(_txt, _x, _y, [_size], [_font], [_alignH], [_alighV])

Set the style and display the text in a single method. See getTimeStamp example on how to use the function.

notify(_on_every_nth_second)boolean

returns true every nth second in draw function

disableRuler()

Removes the ruler graphics from the canvas.

enableRuler()

Ruler for newcomers to show pixel meter.

debug(_itemName)

Create Debug Div cause p5 font is expensive.

Kind: global function

Param Type Description
_itemName Object.<string, number> | Object.<string, string> The argument must be in JSON data format. The function automatically parses "keys" to titles and their "values" next to them. You can add as many objects as you want.

Example (How to use debug() method.)

// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();

utils.debug(
{
   "FPS": frameRate().toFixed(0),
   "Frequency": frequency.toFixed(3)
});

getTimeStamp([_date]) ⇒ String

Timestamp function useful for file naming to avoid overwrite issues.

Kind: global function
Returns: String - Current date + time depending on _date argument value.

When _date = true;

The return format is Year-Month-Day_Hour-Minute-Second

When _date = false;

The return format is Hour-Minute-Second
See: text

Param Type Default Description
[_date] boolean true If true -> Timestamp within Year-Month-Day

Example

// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();

// Font source:
// https://www.dafont.com/lcd-at-t-phone-time-date.font
var cutomFontName = "LCDAT&TPhoneTimeDate.ttf";

function setup() {
  createCanvas(600, 600);
  //noLoop();
}

function draw() {
  background(200);

  // get current time stamp within date
  var currentTime = utils.getTimeStamp();
  //print(currentTime);

  // write it to canvas using utils's text function 
  fill(255, 100, 20);
  utils.text(
    currentTime,        // string to display
    width * 0.5 - 100,   // x position
    height * 0.5 - 60,  // y position
    16
  );

  // get current time stamp without date
  var currentTime2 = utils.getTimeStamp(false);
  fill(90, 90, 90);
  // write it to canvas using utils's text function 
  utils.text(
    currentTime2,   // string to display
    width * 0.5,   // x position
    height * 0.5,  // y position
    80,            // fontsize
    cutomFontName,  // custom font
    CENTER,        // text alignment horizontal
    CENTER);       // text alignment vertical

}

saveCanvas([_prefix], [_suffix])

Utilizes p5JS saveCanvas function to make it easier file saving process by combining the function with getTimeStamp() method.

Kind: global function

Param Type Default Description
[_prefix] String | Number "" Any relevant text in the begining of the file name. If it is leaved empty, the file name will be Year-Month-Day_Hour-Minute-Second.PNG
[_suffix] String "png" The file extension JPG, PNG, ...

Example

var x, y, px, py;
var jump = 10;
var ptime = 2000;

// Init global utils var
var utils = new p5.Utils();
var counter = 0;

function setup() {
  createCanvas(600, 600);

  x = width * 0.5;
  y = height * 0.5;
  px = x;
  py = y;
  background(180);
}

function draw() {
  //background(180, 1);
  px = x;
  py = y;


  // Basic random walker algorithm
  var dice = random();

  if (dice < 0.25) {
    x += jump;
  } else if (dice < 0.5) {
    x -= jump;
  } else if (dice < 0.75) {
    y += jump;
  } else {
    y -= jump;
  }

  strokeWeight(5);
  stroke("#ffcc00");
  noFill();
  beginShape();
  vertex(x, y);
  vertex(px, py);
  endShape();

  // Automated saveCanvas for every 10th second
  if (utils.notify(10) == true && counter < 4) {
    ptime = millis();

    // save current canvas image with default attributes
    utils.saveCanvas();

    // or you can set prefix and file extension argument
    // utils.saveCanvas("randomWalker","jpg");

    // clear the canvas again
    background(180);


    // set starting position to middle of the canvas
    x = width * 0.5;
    y = height * 0.5;
    px = x;
    py = y;

    counter++;
  }

}

arrayResize(_arr, _newSize, [_defaultValue]) ⇒ Array.<Number> | Array.<String> | Array.<Boolean>

Resizes an array and returns it. Similar to vectors resize in C++.

Kind: global function
Returns: Array.<Number> | Array.<String> | Array.<Boolean> - The new array

Param Type Default Description
_arr Array.<Number> | Array.<String> | Array.<Boolean> The array to be resized
_newSize Number The new size of the array
[_defaultValue] Number | String | Boolean -1 Default value for all members of the new array.

Example

// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();
var arr = [];
arr = utils.arrayResize(arr,10);
print(arr);

// or assign default values
arr = utils.arrayResize(arr, 22, random(0,1));
print(arr);

beginShadow(_color, _shadowBlur, _shadowOffsetX, _shadowOffsetY)

Creates shadow effect usign drawing context. Must be used with endShadow method. See examples for how to use it.

Kind: global function

Param Type Description
_color p5.Color | String The color can be declared as color(r,g,b,a) or in hexadecimal format "#FFCC00" as string argument.
_shadowBlur Number Blur amount of the shadow.
_shadowOffsetX Number Shadow offset for x axis.
_shadowOffsetY Number Shadow offset for y axis.

Example

var utils = new p5.Utils();
function setup() {
     createCanvas(400,400);
     rectMode(CENTER);
}

function draw() {
     utils.beginShadow("#000000", 5, 10, 10);
     rect(width*0.5, height*0.5, 100, 100);
     utils.endShadow();
}

endShadow()

Stops shadow effect for the following graphics on the canvas. For example usage beginShadow page.

Kind: global function
See: For example usage beginShadow page.

beginLinearGradient(_colorsArr, _startX, _startY, _endX, _endY, _colorsRatio)

Default Context 2D Gradient fill style. Must be used with endLinearGradient method. See examples for how to use it.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient

Kind: global function

Param Type Description
_colorsArr Array.<p5.Color> | Array.<Number> | Array.<String> List of colors in the gradient fill.
_startX Number The x-axis coordinate of the start point.
_startY Number The y-axis coordinate of the start point.
_endX Number The x-axis coordinate of the end point.
_endY Number The y-axis coordinate of the end point.
_colorsRatio Array.<Number> The distribution weight of colors. The values must be between 0 - 1. Conventionally, if you include three colors, set the first one to 0, the last one to 1, and the middle one depends on your choice(0-1). The method automatically assign start and stop values, if you do not specify any value they will be generated randomly.

Example

// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();

function setup() {
  createCanvas(600, 600);
  noLoop();
}

function draw() {

  background(220);

  noStroke();

  // Begin gradient fill
  utils.beginLinearGradient(
    ["#FFCC00", color(34, 116, 165), color(126, 161, 114)],//Colors
    width * 0.5 - 100,    // gradient begin point x     
    height * 0.5 - 100,   // gradient begin point y
    width * 0.5 + 100,    // gradient end point x
    height * 0.5 + 100,   // gradient end point y
    [0, 0.5, 1]           // Position of each color.
  );

  circle(width * 0.5, height * 0.5, 400);

  // End gradient fill
  utils.endLinearGradient();
}

function keyPressed() {
  if (key == 's')
    utils.saveCanvas("linearGradientFill");
}

endLinearGradient()

Stop Gradient fill for the following graphics. Must be used with beginLinearGradient method. See examples for how to use it.

Kind: global function
See: For example usage beginLinearGradient page.

text(_txt, _x, _y, [_size], [_font], [_alignH], [_alighV])

Set the style and display the text in a single method. See getTimeStamp example on how to use the function.

Kind: global function

Param Type Default Description
_txt String | Number Text or number to be displayed
_x Number X position of the text
_y Number Y position of the text
[_size] Number 12 Font size
[_font] String "sans-serif" Custom Font face. See example getTimeStamp
[_alignH] Constant LEFT Text horizontal align
[_alighV] Constant TOP Text vertical align

notify(_on_every_nth_second) ⇒ boolean

returns true every nth second in draw function

Kind: global function
See: saveCanvas method for the example.

Param Type Description
_on_every_nth_second Number Set notifier frequency. The input value needs to be in seconds.

Example

if (utils.notify(10) == true) {
     // do something here.
}

disableRuler()

Removes the ruler graphics from the canvas.

Kind: global function
See: For example usage enableRuler page.

enableRuler()

Ruler for newcomers to show pixel meter.

Kind: global function
See: disableRuler
Example

// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();

function setup() {
     createCanvas(400,400);
     
     // No need to run in draw function
     // The function creates its canvases in a different drawing context
     utils.enableRuler();
}

function draw() {
     background(220);
     rect(width*0.5, height*0.5,500, 500);
}

function keyPressed() {
     if(key == 'h') {
         utils.disableRuler();
     }
}
You might also like...

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

Improve Response Time 10X by Introducing an Interceptor In NestJS

Improve response times 10x by introducing an interceptor in NestJS This sample project demonstrates the usage of interceptors for improving response t

Oct 28, 2022

An on-demand peer tutoring platform by students, for students.

OURFinals An on-demand peer tutoring platform by students, for students. Database The prisma/ folder contains: migrations/: Past database migrations (

Jan 6, 2022

An obsidian plugin that give additional features to code blocks.

An obsidian plugin that give additional features to code blocks.

Obsidian Advanced Codeblock Add additioinal features to code blocks. Demo Feature Add line numbers to code block Add line highlight to code block Usag

Jan 3, 2023

For some realizations of the title and thinking of the book Introduction to Algorithms, if there is something wrong, please correct me.

Introduction-to-Algorithms Introduce Origin of this library Some implementations of the topics in Introduction to Algorithms and some reflections on t

Jun 9, 2022

Free & Open Source Version of Kneaver Thinking Box

kneaver-open Free & Open Source Version of Kneaver Thinking Box This is a very initial submission. barely more than a boilerplate. There is no warrant

Jan 17, 2022

Don't waste time looking at what you are typing, spend time thinking about the meaning.

Don't waste time looking at what you are typing, spend time thinking about the meaning.

LETA Don't waste time looking at what you are typing, spend time thinking about the meaning. About You will be able to: Practice touch typing Pick bes

Dec 15, 2022

SET Revision is a website to help you identify "sets" in the card game SET.

Welcome to SET Revision! SET Revision is a website to help you identify "sets" in the card game SET. The code in this repository is aimed for learners

Oct 3, 2022
Comments
  • release link...

    release link...

    hey, that link on the readme looks different when you are not the repo owner... on from ["Releases" page](https://github.com/alptugan/p5.utils/releases/download/v0.0.1/p5.utils.min.js).

    should point to: https://github.com/alptugan/p5.utils/releases

    or https://github.com/alptugan/p5.utils/releases/download/v0.1.2/p5.utils.min.js

    regards

    opened by moebiussurfing 2
Releases(v0.1.2)
Owner
alp tuğan
creative coder / part-time instructor / co-founder @FilikaDesign
alp tuğan
A map for 1337 Khouribga's new labs clusters. This tool will help 1337 students find available posts, and search for other students in the cluster by name or login.

1337KH Labs Clusters Map Hellow. This tool is made by 1337 Khouribga students for 1337 Khouribga students to help make their lives at the school easie

Oussama 18 Aug 8, 2022
Data structures & algorithms implementations and coding problem solutions. Written in Typescript and tested with Jest. Coding problems are pulled from LeetCode and Daily Coding Problem.

technical-interview-prep Data structures & algorithms implementations and coding problem solutions. Written in Typescript and tested with Jest. Coding

Lesley Chang 7 Aug 5, 2022
A public board for all the Computer Society and Students to display their profile. An online year-book for you to display your profile in the most creative manner

Student's Yearbook by IEEE Computer Society Student's yearbook is an open-source project which intends to dispaly the students who will be graduating

IEEE Computer Society 11 Dec 18, 2022
A platform designed specifically as an additional layer on top of Google Classroom for students to gain the best out of online evaluations

Peer-Learning-Platform A platform designed specifically as an additional layer on top of Google Classroom for students to gain the best out of online

Rahul Dhakar 3 Jun 12, 2022
In game dev, generative art, and creative coding, sine is a ubiquitous function that is often used as a spring-like oscillator for a given parameter.

In game dev, generative art, and creative coding, sine is a ubiquitous function that is often used as a spring-like oscillator for a given parameter.

Mark Racette 3 Feb 22, 2022
Amelia is an open-source creative-coding toolkit for modern JavaScript

amelia Amelia is an open-source creative-coding toolkit for modern JavaScript. Amelia is a collection of APIs meant to make it easy to create sketches

null 12 Jun 10, 2022
A (very) minimalist creative coding playground. Make animations using only 64 HTML sliders!

Sliderland A (very) minimalist creative coding playground. Make animations using only 64 HTML sliders! Credits The recording feature uses ffmpeg.wasm

null 181 Dec 30, 2022
Salazar - a Discord bot that is easy to customize and configure, aiming at the possibility of customization for the user

Salazar is a Discord bot that is easy to customize and configure, aiming at the possibility of customization for the user. This is the BETA version, which uses the current version of Node.js.

guto 5 Dec 7, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
The /r/place Atlas is a project aiming to catalog all the artworks created during Reddit's 2022 /r/place event.

The 2022 Place Atlas The /r/place Atlas is a project aiming to catalog all the artworks created during Reddit's 2022 /r/place event. This project was

Place Atlas 397 Dec 28, 2022