How i extends class in p5.js?

Yes, it is possible. But in order to use an extended p5 subclass, you’re gonna need to write your code using the dreadful “instance mode” approach: :roll_eyes:

“index.html”:

<script defer src=https://CDN.JsDelivr.net/npm/p5></script>
<script defer src=sketch.js></script>

“sketch.js”:

/**
 * Class p5 Extended (v1.0.1)
 * GoToLoop (2018-Jun-13)
 * https://Discourse.Processing.org/t/how-i-extends-class-in-p5-js/894/5
 */

"use strict";

class p5Plus extends p5 {
  square(x, y, size) {
    return this.rect(x, y, size, size);
  }
}

function mySketch(p) {
  const RATIO = .75, BOLD = 3.5;

  p.setup = function () {
    p.createCanvas(p.displayWidth * RATIO, p.displayHeight * RATIO);
    p.rectMode(p.CENTER).colorMode(p.RGB).noLoop();
    p.fill('yellow').stroke('red').strokeWeight(BOLD);
  };

  p.draw = function () {
    p.background(0).square(p.width >> 1, p.height >> 1, p.width >> 1);
  };
}

new p5Plus(mySketch);
1 Like