Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create multiple canvas elements on same page using p5js

I tried using p5js to draw some points it does work well but I also wanted another canvas element which can show the live video from camera. When I added another canvas element the first canvas goes blank. For now I tried using multiple javascript files to process different canvas.

camera.js

var capture;

function setup() {
  var video=createCanvas(390, 240);
  capture = createCapture(VIDEO);
  capture.size(320, 240);
  capture.hide();
  //set parent to div with id left
  video.parent("left");
}

function draw() {
  background(255);
  image(capture, 0, 0, 320, 240);
  filter('INVERT');
}

drawshapes.js

function setup() {
  // Create the canvas
  var plot=createCanvas(720, 400);
  background(200);
  //set parent to div with id right
  plot.parent("right");
  // Set colors
  fill(204, 101, 192, 127);
  stroke(127, 63, 120);

  // A rectangle
  rect(40, 120, 120, 40);
  // An ellipse
  ellipse(240, 240, 80, 80);
  // A triangle
  triangle(300, 100, 320, 100, 310, 80);

  // A design for a simple flower
  translate(580, 200);
  noStroke();
  for (var i = 0; i < 10; i ++) {
    ellipse(0, 30, 20, 80);
    rotate(PI/5);
  }
}

index.html

<div class="container">
  <div id="left"></div>
  <div id="right"></div>
</div>
like image 287
Adarsh Nair Avatar asked May 15 '16 15:05

Adarsh Nair


People also ask

Can you have multiple canvases in p5js?

This is mentioned briefly on the official p5js reference. Calling createCanvas more than once in a sketch will result in very unpredicable behavior. If you want more than one drawing canvas you could use createGraphics (hidden by default but it can be shown).

Can you have multiple canvas?

Welcome to the Canvas Community. And Yes, you can have multiple Canvas accounts associated in the app.

Does p5js use canvas?

The Default CanvasThe p5. js library will create a default canvas with a width of 100 pixels and a height of 100 pixels when no arguments are provided for the createCanvas() function.


1 Answers

You would want to use instance mode. The first few examples use Global Mode and the next few examples use Instance Mode. Instead of using the default canvas, in instance mode you control where p5js puts the canvas element. If you have two containers, you would use:

new p5(leftSketch, 'left'); new p5(rightSketch, 'right');

leftSketch and rightSketch would be functions that take a variable p. That variable is an instance of p5js and you can control each canvas element separately.

like image 133
psoulos Avatar answered Sep 19 '22 05:09

psoulos