setAlpha() and push()/pop()

Should setAlpha() work as expected within a push/pop block? So far I've not had any success with this.

Modifying the example from the reference:

function setup() {
  ellipse(0, 50, 33, 33); // Left circle
  var c = color(204, 153, 0);

  push(); // Start a new drawing state
  strokeWeight(10);
  c.setAlpha(100);
  fill(c);
  translate(50, 0);
  ellipse(0, 50, 33, 33); // Middle circle
  pop(); // Restore original state

  fill(c);
  ellipse(100, 50, 33, 33); // Right circle
}

The right circle fill(c) is also alpha adjusted, even though outside push/pop. Is this by design?

Answers

  • This depends on what you mean by "as expected". How do you expect this to work?

    I would not expect colors to be affected by push() or pop(). Those functions only affect transformations like translate() and rotate().

  • from the reference:

    push() stores information related to the current transformation state and style settings controlled by the following functions: fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), textFont(), textMode(), textSize(), textLeading().

  • Hmm interesting, guess I learned something new today!

    But notice that the color.setAlpha() function is not listed in those functions.

  • edited March 2018

    In Processing(Java), pushMatrix() and pushStyle() are discrete -- in p5.js it looks like they are combined.

    When you push and pop, the states of the global variables controlled by fill(), stroke(), tint() etc. are pushed / popped.

    But in your case, you created a variable -- var c. That isn't a built-in Processing setting, it is your variable, and it isn't handled by push/pop.

    Instead: set the fill state, push, change the fill state, then use pop to access the previous fill state.

    Something like this...?

    function setup() {
      var c = color(204, 153, 0);
      var c2 = color(204, 153, 0, 100);
    
      fill(c);
      ellipse(0, 50, 33, 33); // Left circle
    
      push(); // Start a new drawing state
      fill(c2);
      strokeWeight(10);
      translate(50, 0);
      ellipse(0, 50, 33, 33); // Middle circle
      pop(); // Restore original state
    
      ellipse(100, 50, 33, 33); // Right circle
    }
    

    Not that if you aren't drawing anything at all before you push then there is little point in using push.

  • I think I understand. Reassigning a variable changes its memory content regardless of setAlpha() or any other method, and push/pop has no bearing on that.

    Thank you both for your time and your thoughts!

Sign In or Register to comment.