Dozed12
Dozed12

Reputation: 95

P5.js Get current fill/stroke color?

I'm developing a addon library for p5.js and I need to setup several fill/stroke colors in certain functions.

Is there a way to get the current fill/stroke value so I can ensure that when the user calls said functions he doesn't have to worry about the colors that I set?

Something of this sort:

function foo(){
    var tempColor = getFill();   //Hypothetical get color function 
    // ...
    fill(color1);                //Some color I use
    // ...
    fill(color2);                //Another color I use
    // ...
    fill(tempColor);             //Reset fill color to user set
}

Edit: Although undocumented, I found some references in p5.js to a curFillColor variable but I didn't find a way to use this.

Upvotes: 9

Views: 2980

Answers (3)

Zlosk
Zlosk

Reputation: 11

Per the p5 reference, the 'drawingContext' system variable provides direct access to the sketch's canvas element, so getStroke and getFill functions can be...

function getStroke() {
    return color(drawingContext.strokeStyle);
}

function getFill() {
    return color(drawingContext.fillStyle);
}

The functions deal with color only; I have not yet found a way to access alpha.

Upvotes: 0

Jithin Ks
Jithin Ks

Reputation: 529

Hey I don't know if its a bit late. I'm also trying to create an addon library for p5. So what I'm doing is I'm calling push just before I'm using the fill and after that call pop. So that I ensure that the fill is restored.

Refer https://p5js.org/reference/#/p5/push

Upvotes: 6

Kevin Workman
Kevin Workman

Reputation: 42176

P5.js is open source, so you can see exactly what they do when you call the fill() function here:

p5.prototype.fill = function() {
  this._renderer._setProperty('_fillSet', true);
  this._renderer._setProperty('_doFill', true);
  this._renderer.fill.apply(this._renderer, arguments);
  return this;
};

Which takes you to the renderer-specific fill variable. You can track that down, but basically: there isn't an easy way to get the current fill color.

What you might want to do is to use a buffer in your library. Don't call fill() on the main sketch; call fill() on the buffer. Do all your drawing to the buffer, and then draw that buffer to the sketch.

Upvotes: 5

Related Questions