1

我有一个我已经完成的 Raphael.js 图像,它由一组圆圈组成,就像这样

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

我还有一个 Raphael 格式的 svg 图标(感谢可爱的网站http://readysetraphael.com/),我想将它放在每个圆圈内。问题是......转换后的 svg 图标中的所有路径现在都相对于点 (0,0) !这意味着所有的字符串都是这样写的

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

所以我的问题......是否有一些聪明的方法可以“相对化”这条路径以使其位于每个圆圈内,而无需手动进入并更改路径字符串的每个元素以使其在内部绘制相同的路径两次两个圈子?

4

1 回答 1

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 );

在这里摆弄

于 2012-10-15T02:16:21.130 回答