# Shared library for simple functions

**URL:** <https://discourse.processing.org/t/shared-library-for-simple-functions/18374>\
**Category:** Development\
**Created:** [March 4, 2020, 12:30am UTC](https://discourse.processing.org/t/shared-library-for-simple-functions/18374 "2020-03-04T00:30:36Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [March 5, 2020, 6:44am UTC](https://discourse.processing.org/t/shared-library-for-simple-functions/18374/4 "2020-03-05T06:44:31Z")

</div>

> [@podryna](#):
>
> But even this edit of “index.html” is beyond them.

The “index.html” file can be written as short as this: 🤠

```auto
<script src=https://cdn.JsDelivr.net/npm/p5></script>
<script src=https://po4599.GitHub.io/javascript/grid.js></script>
<script src=sketch.js></script>

```

> [@podryna](#):
>
> Think issues with single quote vs. double quote, or colon vs. semi-colon.

Take another look at the short “index.html” above and you won’t spot any quotes or anything like it! 😛

> [@podryna](#):
>
> Ideally I’d like to share a library with all of my students, so they just need to add `grid();` into their code to see a grid.

How about instead coding your “grid.js” library in such a way that it seamlessly injects itself into the p5js library as part of its API? 😮

The best moment to draw your grid is right after the **draw()** callback returns. 🖌

p5js got an undocumented method exclusive for 3rd-party libraries named **registerMethod()** which allows us to register our own callback functions: 🙈  
[https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L593-L599](https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L593-L599)

Which are later on called back on 4 specific moments: 🧐  
[https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L715-L716](https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L715-L716)

For example, the _init[]_ registered functions are called back when the sketch is still being initialized:  
[https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L494-L499](https://github.com/processing/p5.js/blob/1.0.1/src/core/main.js#L494-L499)

While _pre[]_ & _post[]_ respectively happen just before & after **draw()** is called back:  
[https://github.com/processing/p5.js/blob/1.0.1/src/core/structure.js#L392-L399](https://github.com/processing/p5.js/blob/1.0.1/src/core/structure.js#L392-L399)

So basically it’s just a matter of invoking **registerMethod()** to register **grid()** as a “post” category callback. 😇

In the version I’ve come up w/ your **grid()** function was rewritten in such a way it’s compatible to both global & instance mode sketches: 🌐

- [Archived Content · processing/p5.js Wiki · GitHub](http://GitHub.com/processing/p5.js/wiki/Archived-Content#instantiation-cases)

And while I was at it, I’ve also added 3 new methods (**toggleGrid()**, **showGrid()** & **isGridVisible()**) to p5js’ API so the grid display can be toggled on/off. 🤩

You can see an online demo along its full source on this link below: 🔗

> **[Register Method Post Draw](https://glitch.com/~register-method-post-draw)**
>
> Simple, powerful, free tools to create and use millions of apps.

And that same demo sketch running now on full page: 🏃‍♂️  
[Register-Method-Post-Draw.Glitch.me](http://Register-Method-Post-Draw.Glitch.me)

I’m also gonna leave all the 3 source code files posted here as well: 🕶

* * *

## “index.html”:

```auto
<script defer src=https://cdn.JsDelivr.net/npm/p5></script>

<script defer src=grid.js></script>
<!-- <script defer src=https://Register-Method-Post-Draw.Glitch.me/grid.js></script> -->

<script defer src=sketch.js></script>
<!-- <script defer src=https://Register-Method-Post-Draw.Glitch.me/sketch.js></script> -->

```

* * *

## “sketch.js”:

```javascript
'use strict';

const FRAMES_TO_TOGGLE = 5,
      ALL_COLORS = 0x1000,
      RGB_COMPONENTS = 3;

function setup() {
  createCanvas(1200, 600).mousePressed(redraw);
  noLoop();
}

function draw() {
  background('#' + hex(~~random(ALL_COLORS), RGB_COMPONENTS));
  frameCount % FRAMES_TO_TOGGLE || print(toggleGrid().isGridVisible());
}

```

* * *

## “grid.js”:

```auto
/**
 * Register Method Post Draw (v1.2.3)
 * GoToLoop (2019-Mar-05)
 *
 * Discourse.Processing.org/t/shared-library-for-simple-functions/18374/4
 * Glitch.com/~matter-js-bouncing-colorful-balls
 */

'use strict';

p5.prototype.registerMethod('init', function initGrid() {
  this._gridIsVisible = true;

  this._gridStyles = {
    'FILL': 'yellow', // 0o200
    'STROKE': 0o250,
    'BOLD': 1,
    'GRID': 10,
    'OFF_X': 2,
    'OFF_Y': 12,
    'TEXT': {
      'FILL': 0o350, // 0
      'SIZE': 11,
      'OFFSET_X': 60,
      'OFFSET_Y': 2,
      'FONT': 'Courier',
      'STYLE': this.BOLD,
      'HOR': this.LEFT,
      'VER': this.BASELINE
    }
  };
});

p5.prototype.registerMethod('post', function grid() {
  const ctx = this == window && p5.instance || this;
  if (!ctx._gridIsVisible | ctx._renderer.isP3D) return;

  const { width: w, height: h, mouseX, mouseY, _gridStyles } = ctx,
        { FILL, STROKE, BOLD, GRID, OFF_X, OFF_Y, TEXT } = _gridStyles,
        stepX = w / GRID, stepY = h / GRID,
        loc = mouseX + ',' + mouseY;

  ctx.push();
  ctx.resetMatrix().fill(FILL).stroke(STROKE).strokeWeight(BOLD);

  ctx.textFont(TEXT.FONT).textStyle(TEXT.STYLE);
  ctx.textSize(TEXT.SIZE).textAlign(TEXT.HOR, TEXT.VER);

  for (var y = 0; y < h; y += stepY) for (var x = 0; x < w; x += stepX) {
    ctx.line(x, 0, x, h).line(0, y, w, y);
    x || ctx.text(Math.round(y), OFF_X, y - OFF_X);
    y || ctx.text(Math.round(x), x + OFF_X, OFF_Y);
  }

  ctx.fill(TEXT.FILL).text(loc, w - TEXT.OFFSET_X, h - TEXT.OFFSET_Y);
  ctx.pop();
});

p5.prototype.toggleGrid = function () {
  this._gridIsVisible = !this._gridIsVisible;
  return this;
};

p5.prototype.showGrid = function (visible=true) {
  this._gridIsVisible = !!visible;
  return this;
};

p5.prototype.isGridVisible = function () {
  return this._gridIsVisible;
};

```

* * *

---

_[View the full topic](https://discourse.processing.org/t/shared-library-for-simple-functions/18374)._
