2012-05-23 16 views
0

我嘗試通過拉斐爾框架的svg功能(它的路徑文檔是here)。我發現編寫路徑字符串非常乏味,因爲在創建新路徑或查看已寫入的路徑時,我必須不斷查找格式規範。有沒有簡化這個過程的框架?例如,而不是寫類似:更容易定義SVG路徑字符串的框架實用程序?

function pathStringForBoxWithQuad(x1, y1, x2, y2) { 
    var edgeLength = 8; 
    var str = "M " + (x2 + edgeLength) + " " + y1; // move to top right 
    str += " L " + x1 + " " + y1; // line to top left 
    str += " L " + x1 + " " + y2; // line to bottom left 
    str += " L " + (x2 + edgeLength) + " " + y2; // line to bottom right 
    str += " Q " + x2 + " " + (y1 + (y2 - y1)/2) + " " + (x2 + edgeLength) + " " + y1; // quadratic back to top right 
    str += " Z"; 
    return str; 
} 

你可以寫類似下面的,但它會給出相同的字符串返回:

function pathStringForBoxWithQuad(x1, y1, x2, y2) { 
    var edgeLength = 8; 
    var str = new SVGPathString() 
      .moveTo(x2 + edgeLength, y1) 
      .lineTo(x1, y1) 
      .lineTo(x1, y2) 
      .lineTo(x2 + edgeLength, y2) 
      .quadTo(x2, (y1 + (y2 - y1)/2), x2 + edgeLength, y1); 
    return str; 
} 

是否像第二種方法任何東西存在流行的框架?我發現這種類型的路徑建設更加友好。

回答

1

我也在尋找類似的東西,但現在我結束了使用Underscore.js爲SVG命令創建模板。像..

var commands = { 
    line: _.template('M<%= x1 %>,<%= y1 %> L<%= x2 %>,<%= y2 %>'), 
    ..... 
} 
.... 
commands.line({ 
    x1: 0, 
    y1: 0, 

    x2: 0, 
    y2: 10   
}) 
+0

這是一個有趣的DIY方法。比我提出的更詳細一點,但肯定比目前提供的路徑語法更具信息性。 –

0

總是有SVG的DOM。

var path = document.getElementById("<pathId>"); 
    var segments = path.pathSegList; 

當你需要創建新的路徑段,你需要使用像

var newSegment = path.createSVGPathSegArcAbs(...) 

呼叫segments.appendItem或segments.insertItemBefore方法來添加。有關更多詳細信息,請參閱http://www.w3.org/TR/2003/REC-SVG11-20030114/paths.html#DOMInterfaces

1

你想要的東西看起來有點類似於SVG Tiny 1.2中的SVGPath API,不需要字符串化。這些路徑對象並不意味着浪費時間序列化,而是直接分配它們。在所有當前的瀏覽器中,SVGPath API僅由Opera AFAIK實現。

雖然SVG工作組正在研究改進SVG2的路徑API,但希望未來會有更好的東西。

+0

很高興知道他們仍在爲此工作,感謝您的信息 –

相關問題