2012-10-15 47 views
1

我有,我已經做了Raphael.js圖像,它由一組圓的,像這樣地方一個拉斐爾JS元素內的另一個

var paper = Raphael(0,0,100,100); 
var circle1 = paper.circ(20,20,10); 
var circle2 = paper.circ(40,40,10); 

我也有在拉斐爾的SVG圖標格式(感謝可愛的網站http://readysetraphael.com/),我想放在每個圈子裏面。問題是...轉換後的svg圖標中的所有路徑現在都相對於點(0,0)!通過這意味着所有的字符串都寫成這樣

paper.path('M 1 1 L 2 0 L 0,2 z') 

所以我的問題......有一些聰明的辦法,以「相對化」這條道路,使其坐在每個圓圈內,不只是要在和每一個變化手工繪製路徑字符串的單個元素,使其在兩個圓圈內繪製相同的路徑兩次?

回答

2

試試這個。用其他有效路徑替換shp的內容。

var shape, 
     circleHalfWidth, 
     circleHalfHeight, 
     shpHalfHeight, 
     shpHalfWidth, 
     targetLeft, 
     targetTop, 
     paper, 
     circle1, 
     circBBox, 
     shpBBox, 
     shp, 
     radius = 20, 
     b2, 
     c2, 
     b, 
     s; 

shape = "M25.979,12.896,5.979,12.896,5.979,19.562,25.979,19.562z"; 
paper = new Raphael(0,0,500,500); 
circle1 = paper.circle(100,100,radius); 
shp = paper.path(shape); 

// get objects that contain dimensions of circle and shape 

circBBox = circle1.getBBox(); 
shpBBox = shp.getBBox(); 

// get dimensions that will help us calculate coordinates to centre of circle 

circleHalfWidth = circBBox.width/2; 
circleHalfHeight = circBBox.height/2; 
shpHalfWidth = shpBBox.width/2; 
shpHalfHeight = shpBBox.height/2; 

// calculate coordinates to position shape on top left corner of circle 

targetLeft = circle1.getBBox().x - shp.getBBox().x; 
targetTop = circle1.getBBox().y - shp.getBBox().y; 

//Calculate how wide is shape allowed to be in circle using pythagoras 

c2 = Math.pow(radius, 2); 
b2 = c2/2; 
b = Math.sqrt(b2); 

// Calculate ratio so that both height and width fit in circle 

s = shpBBox.width > shpBBox.height ? (shpBBox.width/b) : (shpBBox.height/b); 

// change coordinates so shape will be moved to centre of circle 

targetLeft += circleHalfWidth - shpHalfWidth; 
targetTop += circleHalfHeight - shpHalfHeight; 

// Remember uppercase T so that scaling is ignored when moving shape 

shp.transform("s" + s + "T" + targetLeft + "," + targetTop); 

小提琴here