How to fill with HEX color in p5.js

I intend to fill shape with hex color because I’ll use a GUI to allow users to pick color and dat.gui returns a hex value.

The two methods I attempted is either to use red(), green(), blue() on the color or use a hex2tgb conversion code. But somehow neither works.

function setup() {
  createCanvas(500, 500);
  background(255);
  let c = '#D8BFD8' ; 
  

}

function draw() {  

    fill(red(c),green(c),blue(c));
    //fill(hexToRgb(c).r,0,0);
    //fill(0);
    ellipse(100,100,50,50);
}


function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

What would be the best method to use hex color in p5? Thanks

1 Like

Thanks. I can pass in the color control to fill the shape, but if I want to use a lerpcolor between two chosen colors from the control it will throw an error ‘TYPEeRROR: undefined is not an object’

function setup() {
    createCanvas(500, 500);
    background(255);
}


function draw() {
    background(options.Background);
    fill(options.Foreground)
    ellipse(100, 100, 50, 50);
    let intermediate = lerpColor(options.Foreground, options.Background, 0.5);
    fill(intermediate);
    ellipse(200, 100, 50, 50);

}

lerpColor() demands that its 1st & 2nd passed arguments to be of p5.Color datatype:

If options.Foreground & options.Background are an array or a number or even a color string, you can convert them to a p5.Color datatype by passing them as an argument for color():

Extra info about p5.Color:

2 Likes

thanks! didn’t expect the solution to be so simple.