Skip to content

Instantly share code, notes, and snippets.

@ixqbar
Last active August 9, 2019 08:32
Show Gist options
  • Save ixqbar/e4a3b42b0bd2ad8baf615a96d4b0baee to your computer and use it in GitHub Desktop.
Save ixqbar/e4a3b42b0bd2ad8baf615a96d4b0baee to your computer and use it in GitHub Desktop.
bezier曲线点
export const bezier = function (points, times) {
    var bezier_points = [];
    var points_D = [];
    var points_E = [];
    const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0]['y'], 2));
    const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1]['y'], 2));
    const EACH_MOVE_AD = DIST_AB / times;
    const EACH_MOVE_BE = DIST_BC / times;
    const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
    const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
    const RADIUS_AB = Math.atan(TAN_AB);
    const RADIUS_BC = Math.atan(TAN_BC);

    for (var i = 1; i <= times; i++) {
        var dist_AD = EACH_MOVE_AD * i;
        var dist_BE = EACH_MOVE_BE * i;
        var point_D = {};
        if (points[0]['x'] < points[1]['x']) {
            point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
            point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
        } else {
            point_D['y'] = points[0]['y'] - dist_AD * Math.sin(RADIUS_AB);
            point_D['x'] = points[0]['x'] - dist_AD * Math.cos(RADIUS_AB);
        }
        points_D.push(point_D);

        var point_E = {};
        if (points[0]['x'] < points[1]['x']) {
            point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
            point_E['x'] = points[1]['x'] + dist_BE * Math.cos(RADIUS_BC);
        } else {
            point_E['y'] = points[1]['y'] - dist_BE * Math.sin(RADIUS_BC);
            point_E['x'] = points[1]['x'] - dist_BE * Math.cos(RADIUS_BC);
        }

        points_E.push(point_E);

        var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
        var radius_DE = Math.atan(tan_DE);
        var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']), 2));
        var dist_DF = (dist_AD / DIST_AB) * dist_DE;
        var point_F = {};
        if (points[0]['x'] < points[1]['x']) {
            point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];
            point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
        } else {
            point_F['y'] = point_D['y'] - dist_DF * Math.sin(radius_DE);
            point_F['x'] = point_D['x'] - dist_DF * Math.cos(radius_DE);
        }
        bezier_points.push(point_F);
    }

    return bezier_points
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment