2017-10-06 307 views
1

我一直在研究一個特定的動畫,我需要將圓角矩形形狀轉換爲圓形(使用動畫)。我檢查了paper.js的文檔,並沒有找到任何預定義的函數來實現這一點。將圓角矩形變換爲圓形

From this shape - >To This shape

動畫需要是光滑的。由於我正在使用的矩形數量非常大,因此我無法使用「移除當前圓角矩形並重新繪製一個更多圓角版本」方法。它降低了性能,動畫變得遲鈍。

這是我用來生成圓角矩形的代碼。

// 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:如果有任何其他(更好的)技術對物體的顏色進行動畫處理,請分享一下。

回答

4

您首先必須創建一個圓角矩形的路徑。然後,在動畫中的每一步中,都必須修改路徑的八個部分。這隻適用於Path對象,如果您的矩形是Shape,則不適用。

的分段點和手柄必須設置這樣的: rounded rect point and handle position

κ(卡帕)在paper.js被定義爲Numerical.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; 
} 



編輯:我剛剛發現使用形狀更簡單的方法。不確定哪種方法執行速度更快。

這裏是使用ShapeClick 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; 
    } 
} 
+0

非常感謝。所以我說得對,形狀沒有這種功能。現在我必須將所有形狀更改爲路徑。那正是我所需要的。 –

+1

@AkashK。其實我只是找到了一種使用Shape的方法。看看我對新方法的回答的編輯。 – Waruyama

+0

我很想知道你是如何找到這個的?是否有任何我錯過的形狀的文檔或文章。通常情況下,沒有人會考慮設置矩形的半徑:p 我希望我可以再次提出答案。 –

0

更改角落的大小以下

var cornerSize = circle.radius/1;