javascript - 如何计算沿(贝塞尔曲线)移动的 1/4 圆弧?

标签 javascript jquery bezier

我正在使用 JQuery.path沿贝塞尔曲线移动对象。单击该项目时,我可以确定起点和终点。如何计算 Angular 和长度,使元素在与起点和终点相交的 1/4 圆弧上从 A 点移动到 B 点?

我基本上希望它沿着一条永远不会低于起始点 y 的曲线移动位置,永远不要在最后的左边x位置。

    var path = {
        start: {
            x: currentLeft,
            y: currentTop,
            angle: ????, //Don't know how to calculate this
            length: ???? //Don't know how to calculate this
        },
        end: {
            x: endLeft,
            y: endTop,
            angle: ????, //Don't know how to calculate this
            length: ???? //Don't know how to calculate this
        }
    };

    jQuery(myElement).animate(
        {
            path: new jQuery.path.bezier(path)
        }
    );

大约。我想要的是: enter image description here

大概是我得到的(它们浸得太低了): enter image description here

最佳答案

通用解决方案有点棘手,因为它必须处理四个对 Angular 线方向、水平和垂直方向上的对 Angular 线移动。

首先,您需要一些实用函数:

function r2d(x) {
    /* radians to degrees */
    return x * 180 / Math.PI;
}
function smaller(x, y) {
    /* returns the closer of x|y to zero */
    var x_ = Math.abs(x);
    var y_ = Math.abs(y);
    return (Math.min(x_, y_) === x_) ? x : y;
}

现在一个主要函数 anim 接受一个 jQuery 对象(包含感兴趣的元素)和一个 end 对象(具有属性 .left 和 .top )。

function anim($el, end) {
    var current = $el.position();

    var slope1 = (end.top - current.top) / (end.left - current.left);
    var slope2 = 1 / slope1;
    var endAngle = r2d(Math.atan(smaller(slope1, slope2)));
    var startAngle = -endAngle;
    var length = 1/3; //Vary between 0 and 1 to affect the path's curvature. Also, try >1 for an interesting effect.

    //For debugging
    $("#endAngle").text(endAngle);
    $("#startAngle").text(startAngle);
    $("#length").text(length);

    var path = {
        start: {
            x: current.left,
            y: current.top,
            angle: startAngle,
            length: length
        },
        end: {
            x: end.left,
            y: end.top,
            angle: endAngle,
            length: length
        }
    };

    $el.animate({ path: new jQuery.path.bezier(path) });
}

endAngle 的计算对于每种情况(四个对 Angular 线,水平和垂直)都非常简单,但对于通用解决方案来说有点棘手。我花了一段时间才开发出适用于所有情况的东西。

DEMO

关于javascript - 如何计算沿(贝塞尔曲线)移动的 1/4 圆弧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527804/

相关文章:

algorithm - 什么是平滑多个二次贝塞尔曲线的好算法?

javascript - 在 HTML5 Canvas 中绘制箭头曲线

c# - 绘制贝塞尔曲线的半弧

javascript - 如何使用JavaScript/Jquery在 anchor 中显示动态生成的代码

javascript - TypeScript 提示正确的 HTML5 Fullscreen API 方法

Javascript onmouseover 和 onmouseout

javascript - 如何以干净的方式动画和更改 slider 计数器位置?

javascript - JQuery - 单击按钮时更改 $_GET 变量

jquery - 当 showCloseButton 设置为 'false' 时,Fancybox iframe 关闭按钮不会隐藏

javascript - 需要使用 jquery 为两组不同的复选框设置单独的单击事件。