2010-06-18 47 views
0

我有一個Raphaël文本對象,我想圍繞軸旋轉一定距離,並相應地旋轉文本以保持水平。我知道這是可能的使用SVG轉換矩陣,但作者Raphaël has stated that they won't be a part of the toolkit anytime soon。下面是想我做的一些代碼:如何在Raphael文本對象上應用多個旋轉變換?

txt_obj = paper.text(100, 100, "Hello!"); 
txt_obj.rotate(90, 100, 200); // rotate text so it is sideways at (200,200) 
txt_obj.rotate(-90); // rotate text back to horizontal 

不幸的是,第二旋轉命令抹殺第一完成平移和旋轉。

如果我在做直SVG我可以做這樣的事情:

<g transform="rotate(90, 100, 200)"> 
    <text x="100" y="100" transform="rotate(-90, 100, 100)">Hello!</text> 
</g> 

不過,我不相信拉斐爾支持SVG g元素。

理想情況下,我想爲操作設置動畫,但我現在要一步一步地完成操作。

回答

3

這是一個古老的問題,但我只是通過它的方式進行鬥爭,所以我想我會分享我的答案。

您可以直接訪問SVG對象,甚至裏面的拉斐爾來電,正是如此:

this.node.getAttribute('x') 

this.node.getAttribute('transform') 

第二個就是得到我們所需要的。與拉斐爾旋轉文本麻煩的是它是所有設置的轉換在SVG:

<text x="600" y="606.240234375" text-anchor="middle" style="text-anchor: middle; 
font: normal normal normal 10px/normal Arial; font-family: Arial; font-weight: 900; 
font-size: 18px; " font="10px &quot;Arial&quot;" stroke="none" fill="#000000" 
font-family="Arial" font-weight="900" font-size="18px" transform="rotate(45 600 600)"> 
<tspan style="-webkit-user-select: none; cursor: pointer; ">FOOBAR</tspan></text> 

多次調用.rotate()覆蓋以前的設置,以便最終只有一個呼叫在SVG變換旋轉。但是我們可以通過直接訪問屬性來添加自己的變換。變換似乎以相反的順序來執行(或東西 - 老實說,我還沒有想過這個問題太難了),所以你把你的額外的旋轉最後,如果你希望它先去:

<script> 
(function (raphael) { 
    $(function() { 
    var paper = raphael("raphael_div", 500, 500); 

    upside_down_text = paper.text(100,100,'UPSIDE DOWN') 
          .attr('font-family','Arial') 
          .attr('font-size','24px');       
    upside_down_text.rotate(25,250,250); // rotate using Raphael 
    // But first we want to rotate 180 degrees. 
    height = upside_down_text.getBBox().height; 
    upside_down_text.node.setAttribute('transform', 
             upside_down_text.node.getAttribute('transform')+ 
             ' rotate(180 '+ 
             upside_down_text.node.getAttribute('x')+ 
             ' '+ 
             (upside_down_text.node.getAttribute('y')-(height/2))+ 
             ')'); 
    }); 
})(Raphael.ninja()); 
</script> 
<div id="raphael_div"></div> 
+0

這是凌亂和有點破解,但似乎沒有修改Raphael源代碼,這是我必須採取的選項。不錯的工作。 – Pridkett 2011-06-02 20:56:10

+0

謝謝。這是一個殘骸,但它的工作原理。我確實發現了一個問題:如果您使用setAttribute爲該元素提供了一個id,然後嘗試在之後設置transform屬性,那麼它將自動失敗。不知道爲什麼。 – 2011-06-03 00:48:50