如何在贝塞尔曲线中添加渐变?

How to add a gradient in a Bezier curve?

我在地图上绘制了表示客户国家和他要去旅行的国家的曲线。

但我无法添加渐变,以便线条表示所述信息并随机给出两种颜色之间的随机颜色。这是我尝试过的。

int steps = 10;
    noFill();
    //stroke(#5A38FA, 50);
    strokeWeight(1);
    for(int i=0; i<steps; i++) {
      strokeWeight(1);
      noFill();
      stroke(lerpColor(#31B5E8, #F0E62E, (float)i/steps));
      bezier(locationX, locationY, locationX+random(15, 50), locationY+random(13,50), customerLocationX+random(15, 30), customerLocationY+random(15, 70), customerLocationX, customerLocationY);
    }

您可以使用 bezierPoint() 方法将贝塞尔曲线分解为点,然后在连续的点之间绘制直线段,为每个单独的线段指定颜色(当然同时逐渐渐变颜色)。

我在下面的代码示例中生成了一种方法可以做到这一点。

此外,使用该方法,您可以指定曲线的大小(curve) 和曲线的方向(dir);该方法使用垂直于起点(头)和终点(尾)之间的中点的直线上的点计算贝塞尔曲线控制点。

void setup() {
  size(500, 500);
  smooth(4);
  noLoop();
  redraw();
  strokeWeight(5);
  noFill();
}

void draw() {
  background(35);
  drawCurve(new PVector(50, 50), new PVector(456, 490), #31B5E8, #F0E62E, 50, -1);
  drawCurve(new PVector(150, 75), new PVector(340, 410), #B9FF00, #FF00C5, 150, 1);
  drawCurve(new PVector(200, 480), new PVector(480, 30), #007CFF, #89CA7F, 100, 1);
}

void drawCurve(PVector head, PVector tail, color headCol, color tailCol, float curve, int curveDir) {

  final float theta2 = angleBetween(tail, head);
  final PVector midPoint = new PVector((head.x + tail.x) / 2, 
    (head.y + tail.y) / 2);
  final PVector bezierCPoint = new PVector(midPoint.x + (sin(-theta2) * (curve * 2 * curveDir)), 
    midPoint.y + (cos(-theta2) * (curve * 2 * curveDir)));

  PVector point = head.copy();
  for (float t=0; t<=1; t+=0.025) {
    float x1 = bezierPoint(head.x, bezierCPoint.x, bezierCPoint.x, tail.x, t);
    float y1 = bezierPoint(head.y, bezierCPoint.y, bezierCPoint.y, tail.y, t);
    PVector pointB = new PVector(x1, y1);
    stroke(lerpColor(headCol, tailCol, t));
    line(point.x, point.y, pointB.x, pointB.y);
    point = pointB.copy();
  }
}  

static float angleBetween(PVector tail, PVector head) {
  float a = PApplet.atan2(tail.y - head.y, tail.x - head.x);
  if (a < 0) {
    a += PConstants.TWO_PI;
  }
  return a;
}

结果: