Base class for the library

new p5.Utils()
Version: 0.1.0
Author: Alp Tuğan
Related
About the author

Create Debug Div cause p5 font is expensive.

debug(_itemName: (Object<string, number> | Object<string, string>))
Parameters
_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

src/p5.utils.js

Timestamp function useful for file naming to avoid overwrite issues.

getTimeStamp(_date: boolean): string
Parameters
_date (boolean = true) If true -> Timestamp within Year-Month-Day
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

Related
text
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

}

getRandomInt

src/p5.utils.js

Generates and returns a random integer between min and max number

getRandomInt(_min: number, _max: number): number
Parameters
_min (number) Floor value of the random number
_max (number) Ceil value of the random number
Returns
number: Result will be integer

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

saveCanvas(_prefix: (string | number), _suffix: string)
Parameters
_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

src/p5.utils.js

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

arrayResize(_arr: (Array<number> | Array<string> | Array<boolean>), _newSize: number, _defaultValue: (number | string | boolean)): (Array<number> | Array<string> | Array<boolean>)
Parameters
_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.
Returns
(Array<number> | Array<string> | Array<boolean>): 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

src/p5.utils.js

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

beginShadow(_color: (p5.Color | string), _shadowBlur: number, _shadowOffsetX: number, _shadowOffsetY: number)
Parameters
_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();
}

Clears shadow effect for the following graphics on the canvas. For example usage check beginShadow.

endShadow()
Related
beginShadow

beginRadialGradient

src/p5.utils.js

Default Context 2D Radial Gradient fill style. Must be used with endRadialGradient method. See examples for how to use it. Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createRadialGradient

beginRadialGradient(_colorsArr: (Array<p5.Color> | Array<string>), _startX: number, _startY: number, _rad: number, _endX: number, _endY: number, _rOuter: number, _ratio: number)
Parameters
_colorsArr ((Array<p5.Color> | 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.
_rad (number) Radius of the first radiant gradient space.
_endX (number = -1) The x-axis coordinate of the end point. If you leave it as -1, the function set _endX=_startX.
_endY (number = -1) The y-axis coordinate of the end point. If you leave it as -1, the function set _endY=_startY
_rOuter (number = -1) Radius of the outer radiant gradient space. If you leave it as -1, the function set _rOuter=_rad and _rad=_rad*0.1
_ratio (number = -1) 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
// Declare global utils var
var utils = new p5.Utils();
function setup() {
     createCanvas(innerWidth, innerHeight);
}

function draw() {
 background(200);
 utils.beginRadialGradient(
     ["#ffcc00","#ccff00","#ff0000"],
     width*0.5,
     height*0.5,
     100,
     width*0.5 + 100,
     height*0.5 + 100,
     400);
 circle(width*0.5, height*0.5,400);
 utils.endRadialGradient();        

}

endRadialGradient

src/p5.utils.js

Stops radial gradient fill for the following graphics on the canvas. For example usage check beginRadialGradient page.

endRadialGradient()
Related
beginRadialGradient

beginLinearGradient

src/p5.utils.js

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

beginLinearGradient(_colorsArr: (Array<p5.Color> | Array<string>), _startX: number, _startY: number, _endX: number, _endY: number, _colorsRatio: Array<number>)
Parameters
_colorsArr ((Array<p5.Color> | 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

src/p5.utils.js

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

endLinearGradient()
Related
For example usage beginLinearGradient page.

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

text(_txt: (string | number), _x: number, _y: number, _size: number, _font: string, _alignH: Constant, _alighV: Constant)
Parameters
_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

returns true every nth second in draw function

notify(_on_every_nth_second: number): boolean
Parameters
_on_every_nth_second (number) Set notifier frequency. The input value needs to be in seconds.
Returns
boolean:
Related
saveCanvas method for the example.
Example
if (utils.notify(10) == true) {
     // do something here.
}

setRulerStyle

src/p5.utils.js

Customize the pixel ruler style. Set the colors and font options. Also customizes the debug background and text colors.

setRulerStyle(_p5rulerBgColor: string, _p5rulerTxtColor: string, _p5rulersize: number, _p5rulerInfoColor: string, _p5rulerInfoBgColor: string, _p5rulerTickColor: string, _p5rulerFont: string)
Parameters
_p5rulerBgColor (string = "rgba(30,30,30,1)") Pixel Ruler Background color.
_p5rulerTxtColor (string = "rgba(150,150,150,1)") Text Color on the Pixel Puler.
_p5rulersize (number = 20) Ruler size for top and left sides.
_p5rulerInfoColor (string = "rgba(30,30,30,1)") Info Text Color following the mouse cursor.
_p5rulerInfoBgColor (string = "rgba(255,255,255,0.5)") Info Text Background color.
_p5rulerTickColor (string = "rgba(255,0,0,1)") Ticker Color that projects the mouse cursor on top and left ruler bar.
_p5rulerFont (string = "11px monospace") Overall font size and font-family of the Pixel Ruler.
Related
enableRuler
Example
// Define global variable and initialize p5.Utils lib
var utils = new p5.Utils();

function setup() {
     createCanvas(400,400);
     
     // Set styling before the enabling the ruler
     utils.setRulerStyle(
         "rgba(200,200,200,1)", // Ruler Bg Color
         "rgba(30,30,30,1)",    // Ruler Text Color
         20,                    // Ruler Size
         "rgba(200,200,200,1)", // Info Text Color following the mouse cursor
         "rgba(5,5,5,0.7)",     // Info Text Background Color
         "rgba(0,255,0,1)",    // Ticker Color that projects the mouse cursor on top and left ruler bar
         "10px monospace"      // Overall font size and font family
     );    
     
     // 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();
     }
}

disableRuler

src/p5.utils.js

Removes the ruler graphics from the canvas.

disableRuler()
Related
For example usage enableRuler page.

enableRuler

src/p5.utils.js

Ruler for newcomers to show pixel meter.

enableRuler()
Related
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();
     }
}