How do I make "light" turn on and off with a button gradually not in a split second in p5js?

I try using setInterval() but idk. Here is my code before messing with it:

var dark = true;

function setup() {
  createCanvas(250, 250);
  createP('');
  createButton('click me').mousePressed(swap);
}

function draw() {
  dark ?  background(0) : background(0,255,0);
}

function swap() {
  dark = !dark;
}
Tagged:

Answers

  • Maybe look at colorLerp but you need additional vars to tell you how far the process of color change is

  • The code is avaialble in Java (Processing). Maybe you can find it in JS. It is related to fading, transition between two images, etc. Check it out: https://forum.processing.org/two/search?Search=fade

    Kf

  • Need a little bit more help here :/

  • edited May 2017 Answer ✓

    Hi Banana,

    I'm new to P5* myself, I worked your code into the following:

    var direction = -1; // -1 fades down, 1 fades up; direction initialised at -1 so that you have to click the mouse to change direction to fade up
    var fadeColour = 0; // r'G'b value of fading colour starts with black
    
    // change the variables to direction 1 and fadeColour 255 to start off with green instead of black    
    
    function setup() {
      createCanvas(250, 250);
      createP('');
      createButton('click me').mousePressed(swap);
    }
    
    function draw() {
      if (direction == -1 && fadeColour > 0) fadeColour -= 5; // change -=5 to adjust speed of fade
      if (direction == 1 && fadeColour < 255) fadeColour += 5; // change +=5 to adjust speed of fade
      background(0, fadeColour, 0); // change background colour to update the fade
    }
    
    function swap() {
      if (direction == 1) direction = -1; // if we've faded up, change direction to fading down
      else if (direction == -1) direction = 1; // if we've faded down, change direction to fading up
    }
    

    Hope this helps, but as I say I am a novice myself and the links above make good reading. Hope this helps answer your question.

    Snapper

  • edited May 2017

    Thanks yall two for putting up with me and helping me. Snapper, I like how you work with my code. I would change your swap function with:

    function swap() {
      direction *= -1;
    }
    

    We can use boolean here too. I know that from Coding Train youtube tutorials. Right now, I am trying to understand why fadeColour stops at 255 and does not keep going...

  • Hi Banana,

    Yes your updated swap function is the best (shortest / faster) way. fadeColour is set by the two "if" conditions under draw(). In RGB the range is (0 - 255 or old skool - one byte !) Anything above 255 still works but does nothing more to the colour visually it's at the maximum level of, in this case Green. Once Green > 255 the incremental fadeColour+=5; instruction gets ignored because the "if" conditions are no longer true.

Sign In or Register to comment.