2014-11-21 75 views
1

我试图让我的SVG图像适合父容器。不过,我可能误解了一些东西,因为没有任何东西适合我。跨浏览器的方式来强制SVG适合里面div

我试过使用vievBoxpreserveAspectRatio但它没有任何效果。 JS FIDDLE

然后我试着写一个脚本来转换SVG但仍然是不匹配的视框中完美JS FIDDLE 2

不知怎的,在Firefox和Chrome这两个例子在Internet Explorer 11的工作,但没有。

HTML

<div class="svg_box"> 
    <svg id="svg_map" viewBox="0 0 800 400" preserveAspectRatio="xMidYMid meet"> 
    <g id="viewport"> 
     <g id="County_fills"> 
     <g id="wicklow"> 
      <path d="m 660.19812,671.17693 c 4.3002,-24.4434 25.98479,-42.3466 13.668,-66.4151 3.521,-20.6076 -8.00616,-48.1039 -28.42028,-38.027 -11.84916,-7.4307 -15.52234,9.0615 -25.5361,-10.1857 -13.21206,-5.8314 -15.00724,18.141 -19.90659,23.682 -3.4252,15.0746 -22.32726,16.7667 -25.17803,34.5218 -0.30454,15.0967 8.81716,24.9106 24.882,22.849 7.57843,8.1943 17.12841,-1.2087 9.03025,18.9026 -10.09526,5.7923 -29.7139,-17.2323 -30.74574,1.6656 7.44289,0.675 23.28352,39.2398 37.71449,22.0728 5.70401,-21.6558 29.89655,-24.6066 41.068,-9.182 -0.82169,2.7052 6.39378,3.4876 3.424,0.116 z" id="path3626" /> 
     </g> 
     <!-- ... other counties ... ---> 
     </g> 
    </g> 
</svg> 

JS

$('#viewport').each(function() { 
     var objThs = $(this); 

     scaleH = $('#svg_map').innerHeight()/objThs[0].getBoundingClientRect().height; 
     scaleW = $('#svg_map').innerWidth()/objThs[0].getBoundingClientRect().width; 

     if (scaleH < scaleW) { 
      scale = scaleH; 
     } 
     else { 
      scale = scaleW; 
     } 
    centerX = parseInt($('#svg_map').innerWidth() - objThs[0].getBoundingClientRect().width * scale)/2; 
    centerY = parseInt($('#svg_map').innerHeight() - objThs[0].getBoundingClientRect().height * scale)/2; 
     objThs.attr('transform', "matrix(" + scale + ",0,0," + scale + "," + centerX + ","+centerY+")"); 
    }); 

我会,如果有可能,并且不用JS,但JS是聊胜于无;-)真的快乐

任何帮助将不胜感激。

+0

你检查是否innerWidth()和innerHeight()在所有浏览器中的SVG元素的工作。我怀疑它没有。如果正确设置viewBox,则不需要使用JS。你是如何选择你的viewBox值的? – 2014-11-21 12:37:43

+0

我没有使用innerWidth和innerHeight来获得svg尺寸,但父div的大小,以获得svg大小我使用.getBoundingClientRect()。我确定我设置了vieBox错误,但我不明白如何正确设置在这里,你可以看到我的尝试:http://jsfiddle.net/2xw7vu0c/2/ – 2014-11-21 12:42:33

+0

它看起来像我你喜欢你打电话给innerWidth# svg_map,这是svg,而不是div。 – 2014-11-21 22:17:54

回答

2

viewBox属性描述了SVG内容的边界框。浏览器使用它来计算SVG内容的缩放比例,以填充SVG的宽度和高度而不会溢出(取决于您的preserveAspectRatio当然设置)。

在你的情况“0 0 800 400”是错误的。它只覆盖该岛的一部分。更准确的值是“74 58 617 902”。我通过在“视口”元素上调用getBBox()来实现。

http://jsfiddle.net/2xw7vu0c/6/