processing / processing/p5.js

Include the same sketch multiple times on an HTML page

Open
#6,624 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Discussion
Dominant language
JavaScript
Stars
24k
Forks
3.8k
Avg merge
3d 16h
Merged PRs (30d)
25

Description

Topic

I found that the following verbose and kind of annoying syntax does what I want. I wish there's a way to write it without so much boilerplate:

<div style="display: flex; justify-content: center;">
  <div class="diamond-sketch" style="text-align: center;"></div>
  <div class="diamond-sketch" style="text-align: center;"></div>
  <div class="diamond-sketch" style="text-align: center;"></div>
</div>

<script>
const diamondSketch = (elem) => {
    return (p) => {
        p.setup = function() {
            p.frameRate(10);
            p.rectMode(p.CENTER);
            let canvas = p.createCanvas(100, 100);
            canvas.parent(elem);
            p.background(200);
        };
        p.draw = function() {
            let step = p.frameCount % 100;
            p.background(200);
            let r = (2 * Math.abs(step / 100 - 0.5)) - 0.5;
            p.applyMatrix(1, r, r, 1, 50, 50);
            p.rect(0, 0, 50, 50);
        };
    }
};

document.querySelectorAll('.diamond-sketch').forEach((elem) => {
    new p5(diamondSketch(elem), elem);
});
</script>

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Use the provided HTML example as the reproduction case. Trace how p5 instances are created for multiple matching elements, then define and test a less repetitive supported API; done when the same sketch can be rendered multiple times without the repeated wrapper boilerplate.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend, web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.