Drawing Functions in Instance Mode

I am using instance mode to have multiple canvases on a page. Is there a way to have functions that draw shapes available to either canvas? For example, in the code below, how can I make the drawLine() function work when called?

var l = function( p ) {

      p.setup = function() {
        p.createCanvas(400, 600);
      };

      p.draw = function() {
        drawLine();
      };
 };

function drawLine(){
    line(0,0,100,100);
}

My other solution is to change my functions so they just output numbers, which then get accessed and draw within the draw loop, but if anyone has a solution to the above problem, it would help me a lot! Thanks!

Tagged:

Answers

  • edited November 2015 Answer ✓
    • Main characteristic of all Processing flavors, be it Java Mode, Python Mode, PJS, P5.JS, etc., is that each 1 owns 1 canvas.
    • For example, your function line() there needs to know which canvas it is supposed to "draw".
    • Since drawLine() isn't bound to any p5 instance, it doesn't own a canvas itself.
    • Therefore it can't use P5.JS' drawing APIs directly. :-SS
    • However, we can pass the p5's reference for the canvas which we wish drawLine() to "draw".
      
    <meta charset=utf8>
    <meta name=viewport content=width=device-width,user-scalable=no,initial-scale=1>
    
    <style>body { padding: 0; margin: auto; display: block;
                  width: 400px; height: 600; border: 5px solid green; }</style>
    
    <script src=http://p5js.org/js/p5.min.js></script>
    
    <script>
    
    // forum.Processing.org/two/discussion/13348/drawing-functions-in-instance-mode
    // 2015-Nov-01
    
    const sketch = function (p) {
      p.setup = function () {
        p.createCanvas(400, 600);
        p.background(0350).stroke('red').strokeWeight(5).noLoop();
      };
    
      p.draw = function () {
        drawLine(p);
      };
    };
    
    new p5(sketch);
    
    function drawLine(p) {
      p.line(0, 0, p.width, p.height);
    }
    
    </script>
    
  • Thanks! I tried a bunch of things to link the function with the canvas to no avail, but this works perfectly.

Sign In or Register to comment.