如何用p5创建多个画布?

时间:2019-04-27 10:56:14

标签: 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);
}

1 个答案:

答案 0 :(得分:0)

要使用多个画布,您将需要使用instance mode

与代码的主要区别在于,每套p5.js方法都将在函数内部,并且对p5.js方法的所有调用都需要通过传递给函数的p5实例进行调用。 / p>

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);
<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>