P5.js example

Hi @ea42gh

Thats a great example. Thanks for sharing.

Please note that as long as the communication is from Python to HTML only (unidirectional) you can use the panel.panel.HTML. The WebComponent (or something similar) is needed if you want to have bidirectional communication. I.e. get a mouse position or some other value from the browser to the server.

import param
import panel as pn
pn.extension()
from awesome_panel_extensions.web_component import WebComponent
js_urls = {
    "p5": "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"
}
pn.extension(
    js_files=js_urls
)
p5_html = """
<div id="sketch2" style="float:left;height:10cm;width:10cm;padding-left:5mm;">
    <h1>Sketch2</h1>
</div>
<script type="text/javascript">
target = document.currentScript.parentElement.children[0];

const sketch2 = (p55) => {
// Fourier Series
// Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/125-fourier-series.html
// https://youtu.be/Mm2eYfj0SgA
// https://editor.p5js.org/codingtrain/sketches/SJ02W1OgV

let time = 0;
let wave = [];

let n = 5;

p55.setup = () => {
    p55.createCanvas(600, 400);
    console.log("Created Canvas")
};

p55.draw = () => {
  p55.background(0);
  p55.translate(150, 200);

  console.log("DRAW")
  let x = 0;
  let y = 0;

  for (let i = 0; i < n; i++) {
    let prevx = x;
    let prevy = y;

    let n = i * 2 + 1;
    let radius = 75 * (4 / (n * Math.PI));
    x += radius * Math.cos(n * time);
    y += radius * Math.sin(n * time);

    p55.stroke(255, 100);
    p55.noFill();
    p55.ellipse(prevx, prevy, radius * 2, radius * 2);

    //fill(255);
    p55.stroke(255);
    p55.line(prevx, prevy, x, y);
    //ellipse(x, y, 8);
  }

  wave.unshift(y);

  p55.translate(200, 0);
  p55.line(x - 200, y, 0, wave[0]);
  p55.beginShape();
  p55.noFill();
  for (let i = 0; i < wave.length; i++) {
    p55.vertex(i, wave[i] );
  }
  p55.endShape();

  time += 0.05;

  if (wave.length > 250) {
    wave.pop();
  }
};
};

let myp5_sketch2 = new p5(sketch2, "sketch2");
</script>
"""

p5_sketch = pn.pane.HTML(p5_html, width=350, height=350)
pn.Column(
    p5_sketch,
    sizing_mode="stretch_height",
).servable()
2 Likes