How can I generate a linear gradient along a vector?
Here is the function I'm looking for:
function CreateGradient(x,y, x1,y1,x2,y2) {
// x and y are the point in our image we are looking to create the color for in grayscale
// x1,y1,x2,y2 is the vector in which the linear gradient should run
// Can be in any language
}
What I have so far (that doesn't work):
var width = 2.0;
var offset = 0;
var convX = ((x / RES) * width - width/2) - offset;
var convY = ((y / RES) * width - width/2) - offset;
var angle = Math.atan(y1-y2, x1-x2);
var rx = Math.cos(angle);
var ry = Math.sin(angle);
var here = convX * rx + convY * ry;
var start = x1 * rx + y1 * ry;
var end = x2 * rx + y2 * ry;
var lerpValue = (start - here) / (start - end);
var val = lerp(0,255,clamp(lerpValue,0.0,1.0));
RES is the total resolution of the picture.
val in the value (0-255) which represents the R G and B values of the pixel.
Edit: I have it now thanks code for the future:
var x1 = 0;
var y1 = 0;
var x2 = 255;
var y2 = 255;
var dx = x2-x1;
var dy = y2-y1;
var rx = x-x1;
var ry = y-y1;
var t = ((rx*dx) +(ry*dy)) / ((dx*dx) + (dy*dy));
return lerp(0,255,t);
