Last active
March 2, 2020 11:46
-
-
Save companje/a54deb92be89269c10b4c5ca2b1a8a24 to your computer and use it in GitHub Desktop.
Barycentric Color - triangular interpolation - interpolate between three colors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PVector a = new PVector(100, 100); | |
PVector b = new PVector(200, 100); | |
PVector c = new PVector(150, 200); | |
color red = color(255,0,0); | |
color green = color(0,255,0); | |
color blue = color(0,0,255); | |
void setup() { | |
size(500, 500, P2D); | |
} | |
void draw() { | |
beginShape(TRIANGLE); | |
fill(red); | |
vertex(a.x, a.y); | |
fill(green); | |
vertex(b.x, b.y); | |
fill(blue); | |
vertex(c.x, c.y); | |
endShape(); | |
fill(getBarycentricColor(mouseX,mouseY,a,b,c,red,green,blue)); | |
ellipse(200, 200, 20, 20); | |
} | |
color getBarycentricColor(float x, float y, PVector p1, PVector p2, PVector p3, color a, color b, color c) { | |
PVector t = cartesian2barycentric(x,y,p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); | |
if (t.x<=0 || t.y<=0 || t.z<=0) return color(255); | |
else return color( | |
red(a) * t.x + red(b) * t.y + red(c) * t.z, | |
green(a) * t.x + green(b) * t.y + green(c) * t.z, | |
blue(a) * t.x + blue(b) * t.y + blue(c) * t.z); | |
} | |
//Source: https://observablehq.com/@toja/triangular-color-interpolation | |
PVector cartesian2barycentric(float x, float y, float x1, float y1, float x2, float y2, float x3, float y3) { | |
float y2y3 = y2 - y3, | |
x3x2 = x3 - x2, | |
x1x3 = x1 - x3, | |
y1y3 = y1 - y3, | |
y3y1 = y3 - y1, | |
xx3 = x - x3, | |
yy3 = y - y3, | |
d = y2y3 * x1x3 + x3x2 * y1y3, | |
lambda1 = (y2y3 * xx3 + x3x2 * yy3) / d, | |
lambda2 = (y3y1 * xx3 + x1x3 * yy3) / d; | |
return new PVector(lambda1, lambda2, 1 - lambda1 - lambda2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment