我一直试图让SVG路径出现在我的SVG rect的中间,填充整个svg元素。到目前为止,我已经尝试了以下事情,但无济于事
<g>
标记中,并根据我从elementgetBBox()
获得的值转换组。我会使用这些值,并使用整个SVG框的值来尝试获得正确的数字来缩小元素,但它仍然不适合,也不是居中<svg>
标记而不是<g>
标记。 我遇到的主要问题是:
我有一个jsfiddle of the svg that I'm trying to work with,如果有帮助的话。
答案 0 :(得分:2)
这是一个工作小提琴
此处更改了路径的代码。
<g transform="scale(0.4)">
<path id="star-2-outline" d="M256,128.858l42.98,88.667l97.61,13.478l-71.047,68.278l17.346,96.996L256,349.809l-86.89,46.469l17.346-96.996l-71.047-68.278l97.61-13.478L256,128.858z M256,60.082l-62.978,129.92L49.999,209.75L154.1,309.793l-25.415,142.125L256,383.828l127.315,68.09L357.9,309.793L462.001,209.75l-143.023-19.748L256,60.082z" class="flag-icon" ></path>
</g>
答案 1 :(得分:2)
对于方法#2,如果不清楚路径的边界是什么(你使用的是相对路径命令,那么你的命令不是这样),只需尝试使用viewBox,直到找到正确的边界。对于你的明星来说,结果是(50,55 - 460,455)。
<svg viewBox='0 0 350 200' height='200' width='350' xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="350" height="200" x="0" y="0" fill="#126d62"></rect>
<svg width="350" height="200" x="0" y="0" viewBox="50 55 410 400">
<path id="star-2-outline" d="M256,128.858l42.98,88.667l97.61,13.478l-71.047,68.278l17.346,96.996L256,349.809l-86.89,46.469l17.346-96.996l-71.047-68.278l97.61-13.478L256,128.858z M256,60.082l-62.978,129.92L49.999,209.75L154.1,309.793l-25.415,142.125L256,383.828l127.315,68.09L357.9,309.793L462.001,209.75l-143.023-19.748L256,60.082z" class="flag-icon" ></path>
</svg>
</svg>
对于方法#3,只需要对正确的比例进行处理,然后将其翻译到正确的位置。
<svg viewBox='0 0 350 200' height='200' width='350' xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="350" height="200" x="0" y="0" fill="#126d62"></rect>
<path id="star-2-outline" d="M256,128.858l42.98,88.667l97.61,13.478l-71.047,68.278l17.346,96.996L256,349.809l-86.89,46.469l17.346-96.996l-71.047-68.278l97.61-13.478L256,128.858z M256,60.082l-62.978,129.92L49.999,209.75L154.1,309.793l-25.415,142.125L256,383.828l127.315,68.09L357.9,309.793L462.001,209.75l-143.023-19.748L256,60.082z" class="flag-icon"
transform="scale(0.5) translate(90 -55) "></path>
</svg>
答案 2 :(得分:1)
如果你给你的矩形你想要符合“矩形”的id,那么这将使星星适合矩形:
var rectBBox = rect.getBBox();
var path = document.getElementById("star-2-outline");
var pathBBox = path.getBBox();
var scaleX = rectBBox.width / pathBBox.width;
var scaleY = rectBBox.height / pathBBox.height;
var translateX = rectBBox.x - pathBBox.x;
var translateY = rectBBox.y - pathBBox.y;
path.setAttribute("transform", "scale(" + scaleX + ", " + scaleY + ") translate(" + translateX + ", " + translateY + ")");