p5.js typescript

p5.js typescript


Relocating the canvas

Alternatively, you may want to position your canvas in the midst of other information on your page. This can be done by using p5’s p5.Element.parent() function to move our sketch inside an existing HTML element on our page, rather than leaving it at the very end of the page:

    <title>My Sketch</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.6/p5.js"></script>
    <script src="sketch.js"></script>
    <p>Here is my sketch:</p>
    <div id="sketch-holder">
      <!-- Our sketch will go here! -->
    <p>Pretty cool, eh?</p>
// sketch.js

function setup() {
  var canvas = createCanvas(100, 100);
  // Move the canvas so it’s inside our <div id="sketch-holder">.

  background(255, 0, 200);


Specifying Parent HTML Element

When creating a p5 instance, you can specify a second argument which acts the parent for all elements created by the sketch. For example, let’s say you have:

  <div id = "p5sketch">
    <!-- p5 instance will be created here -->

  <p>Some other HTML</p>

You can now say:

let myp5 = new p5(s, document.getElementById('p5sketch'));

And all elements will be created inside that div.

Here document.getElementById is just a function that takes an id and returns the element with that id.

Writing all that every time would be tedious, so the second argument can also be just an id:

let myp5 = new p5(s, 'p5sketch');

Virtually always the second, short form is good enough. The long form could be necessary if you wanted to use a loop to create more than one p5 instance.

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页