Find Y coordinate along Path.quadTo bezier curve

user5480949 :

Given an X value (or percentage) I need to find the Y coordinate of a point along a Quadratic Bezier curve

The curve is part of a line chart drawn in android using this:

Path.quadTo(prev.x, prev.y, (p.x + prev.x)/2, (p.y + prev.y)/2);

Helder Sepulveda :

The formula to the Quadratic Bezier curve is

x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x;
y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y;

...but I was just testing that on HTML canvas and does not seem to be an exact match.
They might have a custom implementation that slightly differs from that.

You will have to test on android and see, hopefully this sends you on the right path.

var c = document.getElementById("c");
var ctx = c.getContext("2d");

function drawCurve(p) {
  ctx.beginPath();
  ctx.bezierCurveTo(p[0].x, p[0].y, p[1].x, p[1].y, p[2].x, p[2].y);
  ctx.stroke();

  ctx.fillStyle = "red";
  for (var i = 0; i < 100; i++) {  
    ctx.beginPath();  
    t = i/100; 
    x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x;
    y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y;

    ctx.arc(x, y, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
}

drawCurve([
  {x:10, y:120},
  {x:340, y:120},
  {x:340, y:20},
])

drawCurve([
  {x:50, y:10},
  {x:180, y:150},
  {x:240, y:10},
])
<canvas id="c" width="350" height="150"></canvas>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371990&siteId=1