I edited the talkhabis answer (cubic curve) so that the curve displays with the correct coordinates. (I can not comment) It was necessary to change the coordinates of Y (-p []. Y + 150). (A new variable for this may be a better and more efficient solution, but you get the idea)
// Apply points to SVG and create the curve and controllers : var path = document.getElementById('path'), ctrl1 = document.getElementById('ctrl1'), ctrl2 = document.getElementById('ctrl2'), D = 'M ' + p0.x + ' ' + (-p0.y+150) + 'C ' + c0.x + ' ' + (-c0.y+150) +', ' + c1.x + ' ' + (-c1.y+150) + ', ' + p1.x + ' ' + (-p1.y+150); path.setAttribute('d',D); ctrl1.setAttribute('d','M'+p0.x+','+(-p0.y+150)+'L'+c0.x+','+(-c0.y+150)); ctrl2.setAttribute('d','M'+p1.x+','+(-p1.y+150)+'L'+c1.x+','+(-c1.y+150)); // Lets test the "Bezier Function" var t = 0, point = document.getElementById('point'); setInterval(function(){ var p = Bezier(p0,c0,c1,p1,t); point.setAttribute('cx',px); point.setAttribute('cy',-p.y+150); t += 0.01; if(t>=1) t=0; },50); // OK ... Now tring to get "y" on cruve based on mouse "x" : var svg = document.getElementById('svg'), point2 = document.getElementById('point2'); svg.onmousemove = function(e){ var x = (e.pageX - 50)/2, y = (e.pageY - 50)/2; // "-50" because of "50px margin" on the left side // and "/2" because the svg width is 300 units and 600 px => 300 = 600/2 // Get the x,y by mouse x var p = YBX(p0,c0,c1,p1,x); point2.setAttribute('cx',px); point2.setAttribute('cy',-p.y+150); }
http://jsfiddle.net/u214gco8/1/
I also created C code to check the results for a cubic curve. Just enter the X and Y coordinates in the main function.
#include <stdio.h> #include <stdlib.h> #include <math.h> void bezierCurve(int x[] , int y[]) { double xu = 0.0 , yu = 0.0 , u = 0.0 ; int i = 0 ; for(u = 0.0 ; u <= 1.0 ; u += 0.05) { xu = pow(1-u,3)*x[0]+3*u*pow(1-u,2)*x[1]+3*pow(u,2)*(1-u)*x[2] +pow(u,3)*x[3]; yu = pow(1-u,3)*y[0]+3*u*pow(1-u,2)*y[1]+3*pow(u,2)*(1-u)*y[2] +pow(u,3)*y[3]; printf("X: %i Y: %i \n" , (int)xu , (int)yu) ; } } int main(void) { int x[] = {0,75,50,300}; int y[] = {0,2,140,100}; bezierCurve(x,y); return 0; }
https://ideone.com/glLXcB