我不太熟悉在 js 中使用 svgs,但这绝对是奇怪的事情。 我有一个箭头,然后是一条应该在一定程度上填充该箭头的路径。看起来像这样: 现在我的目标是能够缩放白色部分,但它仍然应该留在箭头内 。 现在奇怪的是我不知道如何将白色部分移回正确的位置。我尝试过不同的尝试。 这是我当前的代码(它适用于scaleFactor 1,但不适用于任何其他):
var draw = SVG('arrow').size(500, 500);
var arrowPath=draw.polyline('10,243.495 202.918,15.482 397.199,245.107').fill('none').stroke({ width: 20 });
var arrow=draw.group();
arrow.add(arrowPath.clone());
var scaleFactor=0.5;
var fillArrow=draw.path('M357.669,198.387c-41.747,35.357-95.759,56.678-154.751,56.678c-58.991,0-113.003-21.32-154.75-56.676l154.75-182.907 L357.669,198.387z');
fillArrow.fill('#ffffee');
var moveX=(arrowPath.width()/2-fillArrow.width()/2)/scaleFactor+9.5;
console.log(moveX);
fillArrow.center(arrowPath.cx(), arrowPath.cy()).scale(scaleFactor);
//another attempt was
fillArrow.move(moveX,0);
最佳答案
当您在 SVG 中缩放、旋转和平移时,您正在执行坐标变换。也就是说,您实际上并没有更改正在绘制的对象,而是更改了正在绘制对象的坐标系。将其视为屏幕上具有一定大小的像素,如果您执行 svgObject.scale(0.5 )
像素大小变为一半。
因此,如果您通过 path('M10,10 L20,10 L20,20 L10,20 z')
绘制一个正方形,然后应用 scale(0.5)
它看起来就像您绘制了一条类似 path('M5,5 L10,5 L10,10 L5,10 Z')
一开始这可能听起来很奇怪,但是,当您可以做到这一点时,许多几何计算会变得更加简单。
您想要围绕箭头尖端进行缩放(确保它不会移动)。然后,您应该将该点放置在原点 (0,0)
中,并围绕该点绘制对象。在小组中这样做。因为这样你就可以将组坐标系平移到正确的位置。
var draw = SVG('arrow').size(600, 600);
// create a group
var arrow = draw.group();
// Draw the arrow path in the group
// I have placed the "tip" of the arrow in (0,0)
var arrowPath = arrow.polyline('-250,250 0,0 250,250').fill('none').stroke({
width: 20
});
// Draw the fill arrow in the group. Again, the point
// I which to scale around is placed at (0,0)
var fillArrow = arrow.path('M0,0L150,150,-150,150z').fill('#ffffee');
// Move the group to the position we like to display it in the SVG
arrow.move(260, 20);
var scaleFactor = 0.5
fillArrow.scale(scaleFactor);
这是一个工作示例,您可以在其中测试和更改比例因子。 http://jsfiddle.net/ZmGQk/1/
这里很好地解释了平移、旋转和缩放的工作原理。 http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Transforming_the_Coordinate_System
关于javascript - svg.js 缩放和移动/中心的奇怪交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22481366/