简体   繁体   English

如何设置内联SVG元素的确切大小?

[英]How to set the exact size of an inline SVG element?

I am creating a visualization with d3.js: 我正在使用d3.js创建可视化文件:

http://bl.ocks.org/EE2dev/raw/cd904f10097b9921f1cc/ http://bl.ocks.org/EE2dev/raw/cd904f10097b9921f1cc/

In that code I create an SVG element and set the size with this line: 在该代码中,我创建了一个SVG元素,并使用以下行设置了大小:

var chart = d3.select("body")
  .append("div").attr("class", "chart")
  .append("svg")
  .attr("width", outerWidth) // outerWidth = 960
  .attr("height", outerHeight) // outerHeight = 500
  .append("g")
  .attr("class", "margin")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Testing the code in Chrome, everything works fine, the SVG has the desired size of (960, 500). 在Chrome中测试代码,一切正常,SVG具有所需的大小(960,500)。 When I open this site in Firefox, however, the SVG element is created with a different size, appearantly depending on the actual browser window size, eg (634, 856) in the case below. 但是,当我在Firefox中打开此网站时,SVG元素的创建大小不同,显然取决于实际的浏览器窗口大小,例如,在以下情况下为(634,856)。

在此处输入图片说明

How do I fix this behaviour to set the SVG to the desired fixed size for Firefox? 如何解决此问题,将SVG设置为Firefox所需的固定大小?

I tried several things, including wrapping a div around and/or following ideas I found elsewhere 我尝试了几件事,包括将div包裹起来和/或遵循在其他地方找到的想法

But I didn't find a way to fix this problem for me that worked:( 但是我没有找到一种可行的方法来解决这个问题:(

Any help would be greatly appreciated! 任何帮助将不胜感激!

outerWidth and outerHeight are browsers Window properties. outerWidthouterHeight是浏览器的Window属性。 It is curious problem that these properties could be overwritten in Chrome but not in Firefox ( FF API ). 奇怪的是,这些属性可能会在Chrome中被覆盖,而在Firefox( FF API )中不会被覆盖。 So when you set 所以当你设定

outerWidth = 960;

then outerWidth is changed to 960 in Chrome. 然后在Chrome中将externalWidth更改为960。 In the case of Firefox it is current window width and it can not be changed by the client script. 在Firefox中,它是当前窗口宽度,不能由客户端脚本更改。 So rename outerWidth and outerHeight and it should be working. 因此,重命名outerWidthouterHeight ,它应该可以正常工作。

svgWidth = 960;
svgHeight = 500;

...

.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM