A Polygon2D has a list of vertices. You can use that list in combination with beginShape-endShape and the right renderer to create gradients.
Note that only the P2D, P3D and OPENGL renderers facilitate per vertex color changes (aka gradients) within a beginShape-endShape. With P2D and P3D there may appear white-ish lines in your triangulated shape. With OPENGL there may be jagged edges.
Code Example
- // LEFT mouse button adds points, RIGHT mouse button finalizes shape
- // 'd' deletes polygon, SPACE clears everything
- import toxi.geom.*;
- ArrayList <Polygon2D> polygons = new ArrayList <Polygon2D> ();
- ArrayList <Vec2D> points = new ArrayList <Vec2D> ();
- Vec2D mouse;
- void setup() {
- size(1280,720,P2D);
- noStroke();
- smooth();
- colorMode(HSB,360,100,100,100);
- }
- void draw() {
- background(180,0,100,100);
- mouse = new Vec2D(mouseX,mouseY);
- // draw all the polygons
- for (Polygon2D p : polygons) {
- int numVertices = p.vertices.size();
- beginShape();
- for (int i=0; i<numVertices; i++) {
- Vec2D v = p.vertices.get(i);
- float c = map(i,0,numVertices,0,360);
- fill(c,100,100,50);
- vertex(v.x,v.y);
- }
- endShape(CLOSE);
- }
- // preview shape
- int numPoints = points.size();
- beginShape();
- for (int i=0; i<numPoints; i++) {
- Vec2D v = points.get(i);
- float c = map(i,0,numPoints,0,360);
- fill(c,100,100,50);
- vertex(v.x,v.y);
- }
- endShape(CLOSE);
- // draw all the points
- fill(0);
- for (Vec2D p : points) {
- ellipse(p.x,p.y,5,5);
- }
- }
- void mousePressed() {
- if (mouseButton == LEFT) {
- points.add(mouse);
- } else if (mouseButton == RIGHT && points.size() > 2) {
- // create a polygon from the points
- polygons.add(new Polygon2D(points));
- // clear the points
- points.clear();
- }
- }
- void keyPressed() {
- // clear all points and polygons
- if (key == ' ' && !mousePressed) {
- points.clear();
- polygons.clear();
- }
- // delete the polygon under the mouse
- if (key == 'd' && !mousePressed) {
- for (int i=polygons.size()-1; i>=0; i--) {
- if (polygons.get(i).containsPoint(mouse)) {
- polygons.remove(i);
- }
- }
- }
- }