将圆角矩形转换为圆形

Transform Rounded Rectangle to Circle

我一直在制作一个特定的动画,我需要在其中将(带动画的)圆角矩形转换为圆形。我检查了 paper.js 的文档,但没有找到任何预定义函数来实现此目的。

-->

动画需要流畅。由于我正在处理的矩形数量非常多,我无法使用 "remove current rounded rect and redraw one more rounded version" 方法。它降低了性能并且动画变得滞后。

这是我用来生成圆角矩形的代码。

// Had to paste something to post the question
// Though the whole code can be seen on codepen link
var rect = new Rectangle();
var radius = 100, origin = {x: 100, y: 100};
rect.size = new Size(radius, radius);
rect.center = new Point(origin.x, origin.y);
var cornerSize = radius / 4;
var shape = new Path.Rectangle(rect, cornerSize);

准备此 Codepen 示例以显示进度。

如果我们可以使用任何其他对象类型来制作整个动画,那也很好。现在我找不到任何可以将圆角矩形转换为圆形的属性。

我还在为对象和位置设置动画。我翻阅了很多文档来找出彩色动画。

PS:如果有任何其他(更好的)技术可以使对象的颜色动画化,也请分享。

将边角尺寸改成如下

  var cornerSize = circle.radius / 1;

您首先必须创建一个圆角矩形路径。然后,对于动画中的每一步,您都必须修改路径的八段。这仅适用于 Path 对象,如果您的矩形是 Shape.

则无效

分段点和句柄必须这样设置:

κ (kappa) 在 paper.js 中定义为 Numerical.KAPPA(更多关于 Kappa here)。

更改半径的代码可能如下所示 (Click here for the Sketch):

var rect = new Path.Rectangle(new Point(100, 100), new Size(100, 100), 30);
rect.fullySelected = true;

var step = 1;
var percentage = 0;

function onFrame(event) {
    percentage += step;
    setCornerRadius(rect, percentage)
    if (percentage > 50 || percentage < 0) {
        step *= -1;
    }
}

function setCornerRadius(rectPath, roundingPercent) {
    roundingPercent = Math.min(50, Math.max(0, roundingPercent));
    var rectBounds = rectPath.bounds;
    var radius = roundingPercent/100 * Math.min(rectBounds.width, rectBounds.height);
    var handleLength = radius * Numerical.KAPPA;

    l = rectBounds.getLeft(),
    t = rectBounds.getTop(),
    r = rectBounds.getRight(),
    b = rectBounds.getBottom();

    var segs = rectPath.segments;
    segs[0].point.x = segs[3].point.x = l + radius;
    segs[0].handleOut.x = segs[3].handleIn.x = -handleLength;
    segs[4].point.x = segs[7].point.x = r - radius;
    segs[4].handleOut.x = segs[7].handleIn.x = handleLength;
    segs[1].point.y = segs[6].point.y = b - radius;
    segs[1].handleIn.y = segs[6].handleOut.y = handleLength;
    segs[2].point.y = segs[5].point.y = t + radius;
    segs[2].handleOut.y = segs[5].handleIn.y = -handleLength;
}



编辑: 我刚刚找到了一种更简单的使用形状的方法。不确定哪种方法执行得更快。

这是使用 Shape (Click here for the Sketch).

的实现
var size = 100;
var rect = new Shape.Rectangle(new Rectangle(new Point(100, 100), new Size(size, size)), 30);
rect.strokeColor = "red";

var step = 1;
var percentage = 0;

function onFrame(event) {
    percentage =  Math.min(50, Math.max(0, percentage + step));
    rect.radius = size * percentage / 100;
    if (percentage >= 50 || percentage <= 0) {
        step *= -1;
    }
}