Colour gradients for a triangle

edited September 2017 in How To...

Hello All,

First year student looking for some basic help. I'm trying to fill a triangle with a gradient of grayscale and wondering if this is possible in basic processing language.

Cheers,

James

Answers

  • Here is one way. Notice that you MUST use the P2D render mode for this, because in the default JAVA2D render mode you will just get a white triangle.

    size(400,400,P2D);
    background(128,0,0);
    beginShape();
    fill(0);
    vertex(200,20);
    fill(255);
    vertex(20,380);
    vertex(380,380);
    endShape();
    
  • edited September 2017

    Different approaches to triangles with gradient fills:

    1. As @TfGuy44 suggested, use P2D fill interpolation inside a shape. This works with linear gradients in almost any shape, but only in the P2D renderer, which you can specify as the third argument of size().

    2. For a linear gradient triangle, use a for loop to draw a series of lines, changing the color each time (eg with lerpColor). Add the stroke last. This is easier with an isosceles or right triangle. This is how the linear gradient example works -- just change the length of the line as you go:

    3. For a radial (or nested triangle) gradient, use a for loop to draw a series of nested triangles, from largest to smallest, changing color each time (eg with lerpColor). This is easiest with an equilateral triangle. This is how the radial gradient example works -- just use a triangle instead of a circle.

    4. Fill a PGraphics with an arbitrary gradient, then use a mask to cut out a piece of that gradient in your desired shapes. This is even more flexible then the first example, and works in any renderer, but it requires more coding and more memory/processing overhead if you need a lot of different gradients or if you need to change them every frame.

  • Thanks lads, seem to do the trick

  • @James02135 -- which approach ended up working for you?

  • The script from TfGuy44 was easier for me to both use and understand, I really am just starting out with processing, so once I understand why including the P2D render mode was important, it was easy from there. Thanks again.

  • YAY I'M HELPING 8-}

Sign In or Register to comment.