如何使用p5创建多个画布?

Ant*_*lum 2 javascript p5.js

我想尝试一些 3 维立体视觉的东西,我需要 2 个画布,但我什么也没找到。

我尝试过使用canvas1.background(200);

function setup() {
    let canvas1 = createCanvas(100, 100);
    canvas1.position(0,0);
}
function draw() {
//for canvas 1
    background(100);
    rotateX(frameCount * 0.01);
    rotateZ(frameCount * 0.01);
    cone(30, 50);
}
function setup() {
    let canvas2 = createCanvas(100, 100);
    canvas2.position(100,0);
}
function draw() {
//for canvas 2
    background(100);
    rotateX(frameCount * 0.01);
    rotateZ(frameCount * 0.02);
    cone(30, 50);
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ace 6

要使用多个画布,您需要使用实例模式

与您的代码的主要区别在于,每组 p5.js 方法都将位于函数内部,并且对 p5.js 方法的所有调用都需要由传递到函数中的 p5 实例来调用。

var s1 = function( sketch ) {
  sketch.setup = function() {
    let canvas1 = sketch.createCanvas(100, 100, sketch.WEBGL);
    canvas1.position(0,0);
  }
  sketch.draw = function() {
    //for canvas 1
    sketch.background(100);
    sketch.rotateX(sketch.frameCount * 0.01);
    sketch.rotateZ(sketch.frameCount * 0.01);
    sketch.cone(30, 50);
  }
};

// create a new instance of p5 and pass in the function for sketch 1
new p5(s1);

var s2 = function( sketch ) {

   sketch.setup = function() {
    let canvas2 = sketch.createCanvas(100, 100, sketch.WEBGL);
    canvas2.position(100,0);
  }
  sketch.draw = function() {
    //for canvas 2
    sketch.background(100);
    sketch.rotateX(sketch.frameCount * 0.01);
    sketch.rotateZ(sketch.frameCount * 0.02);
    sketch.cone(30, 50);
  }
};

// create the second instance of p5 and pass in the function for sketch 2
new p5(s2);
Run Code Online (Sandbox Code Playgroud)
<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js'></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.dom.min.js"></script>
Run Code Online (Sandbox Code Playgroud)