How to execute a function when using the createGraphics function ?

I want to use the createGraphics function to draw something on another screen... and then paste that into my main sketck..

in the docu, the example they give is doing something like:

var vignette;

function setup(){
  createCanvas(710, 400);
  vignette = createGraphics(400, 250);
}

function draw(){

  ellipse(mouseX, mouseY, 60, 60);

  pg.background(51);
  pg.noFill();
  pg.stroke(255);
  pg.ellipse(mouseX-150, mouseY-75, 60, 60);

  //Draw the offscreen buffer to the screen with image()
  image(pg, 150, 75);
}

But what i want to do is more complex than pg.background(51)

I want to run this function which creates a radial gradient:

function drawGradient() {
  for (let r = canvasX; r > 0; --r) {
    let lightnes = map(r,0,canvasX,360,0)
    fill(360, 360, lightnes)
    ellipse(0, 0, r, r)
  }
}

But if i do vignette.drawGradient() i get the error: vignette.drawGradient is not a function...

So how can i then execute things like whats inside the drawgradient function inside the createGraphics function?

Here is the codepen: https://codepen.io/giorgiomartini/pen/ZJjWbw?editors=0010

Answers

  • edited August 2017

    The key distinction here is between:

    • draw to the main canvas (background, fill, line, rect, ellipse etc etc etc)
    • draw to a graphics buffer pg ( pg.background, pg.line, pg.rect etc.)

    So your drawGradient function should be calling vignette.fill and vignette.ellipse. If you look at the original example you will see that this is how it works.

  • edited August 2017

    https://CodePen.io/GoSubRoutine/pen/QMBQrZ/right?editors=001

    /**
     * Yellowish Gradient Graphics Circle (v2.0)
     * GiorgioMartini (2017-Aug-24)
     * Mod: GoToLoop
     *
     * Forum.Processing.org/two/discussion/23914/
     * how-to-execute-a-function-when-using-the-creategraphics-function#Item_2
     *
     * CodePen.io/GoSubRoutine/pen/QMBQrZ/right?editors=001
     * CodePen.io/GiorgioMartini/pen/ZJjWbw/right?editors=001
     */
    
    "use strict"
    
    const W = 500, H = 500
    let vignette
    
    function setup() {
      createCanvas(W, H).mousePressed(() => (drawGradient(vignette), redraw()))
      noLoop()
      background('blue').imageMode(CORNER)
    
      vignette = createGraphics(width, height)
      vignette.colorMode(RGB).ellipseMode(CENTER).noStroke()
              .translate(vignette.width>>1, vignette.height>>1)
    }
    
    function draw() {
      image(vignette, 0, 0)
    }
    
    function drawGradient(pg=p5.instance, bg='red', diam=pg.width) {
      pg.background(bg)
    
      while (diam--) {
        const blue = 255 * norm(diam, pg.width, 0) | 0
        pg.fill(255, 255, blue).ellipse(0, 0, diam)
      }
    }
    
Sign In or Register to comment.