缩放&在SVG中居中形状

时间:2017-02-28 18:04:03

标签: javascript svg alignment viewbox

我一直在努力形成在SVG中居中svg形状的逻辑。 viewBox比例函数很好,但是,我使用viewBox来解决形状的居中问题。

Jsbin

以下是代码:

// SCALE & CENTRE THE TEMPLATE ON SCREEN
const svg = document.getElementsByTagName( "svg" )[ 0 ];
const t = document.getElementsByClassName( "templateParent" )[ 0 ];
const svgRect = svg.getBoundingClientRect(),
        svgW = svgRect.width,
        svgH = svgRect.height,
        svgX = svgRect.x,
        svgY = svgRect.y;
const aspectRatio = svgW / svgH;
const tRect = t.getBBox(),
        tW = tRect.width,
        tH = tRect.height,
        tX = tRect.x,
        tY = tRect.y;
const tmW = tW * 1.25,
        tmH = tH * 1.25,
        tmX = tX * 1.25,
        tmY = tY * 1.25;
const vbH = tmH,
        vbW = tmW * aspectRatio,
        vbX = tmX * aspectRatio,
        vbY = tmY;

1 个答案:

答案 0 :(得分:2)

如果您只想将路径移动/缩放到svg的中心,请尝试以下操作:(注意:浏览器不处理viewBox和svg宽度/高度相同,因此我通常在元素上使用变换)< / p>

<!DOCTYPE html>
<html>

<body onload=fit()>
<div style=background:lime;width:600px;height;400px;>
	<svg width="600" height="400" >
		<path id=myPath d="M329.66,99.99l22.1,4H238.43c-1.5-4.3,17.3-85.4,17.3-85.4c1.7-11-10.12-83.7-10.12-83.7l22.1-4 1.405 30.583 61.010 0 1.405 -30.583z" stroke="#bbb" stroke-width="1" vector-effect="non-scaling-stroke" fill="blue" />
	</svg>
</div>

<script>
//---onload---
function fit()
{
	var bb=myPath.getBBox()
	var bbx=bb.x
	var bby=bb.y
	var bbw=bb.width
	var bbh=bb.height
	//---center of path---
	var cx=bbx+.5*bbw
	var cy=bby+.5*bbh

//---Use min of width/height create scale: ratio of desired width vs current width--
var height=400-20 ///--ie padding=20 px--
var scale=height/bbh
//---where to move it: center of svg---
var targetX=300
var targetY=200
//---move its center to target x,y ---
var transX=(-cx)*scale + targetX
var transY=(-cy)*scale + targetY
  myPath.setAttribute("transform","translate("+transX+" "+transY+")scale("+scale+" "+scale+")")
}



</script>
</body>
</html>