Javascript 使用 ViewBox 根据窗口大小调整 svg 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13632169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:32:15  来源:igfitidea点击:

Using ViewBox to resize svg depending on the window size

javascriptsvgd3.js

提问by Jose

I'm attempting to use ViewBox & preserveAspectRatio to automatically adjust my d3.svg.arc when the window size has changed ...

当窗口大小发生变化时,我正在尝试使用 ViewBox & preserveAspectRatio 自动调整我的 d3.svg.arc ...

var svg = d3.select("#chart").append("svg") 
  .append("g")
  .attr("viewBox", "0 0 700 500")
  .attr("preserveAspectRatio", "xMinYMin meet")
  .attr("transform", "translate(" + r + "," + r +") rotate(180) scale(-1, -1)");

I'm a bit confused why it doesn't work at all - I've also attempted to set the preserve to "none" & delete any set margins that I had. yet still no luck - any help or advice would be appreciated.

我有点困惑为什么它根本不起作用 - 我还尝试将保留设置为“无”并删除我拥有的任何设置边距。但仍然没有运气 - 任何帮助或建议将不胜感激。

Here's an example: http://jsfiddle.net/xwZjN/53/

这是一个例子:http: //jsfiddle.net/xwZjN/53/

回答by methodofaction

You are applying viewBoxand preserveAspectRatioto the gelement, they need to be applied to the svgelement:

你申请viewBoxpreserveAspectRatiog元素,需要将它们应用于svg元素:

var svg = d3.select("#chart").append("svg") 
  .attr("viewBox", "0 0 700 500")
  .attr("preserveAspectRatio", "xMinYMin meet")
     .append("g")
     .attr("transform", "translate(" + r + "," + r +") rotate(180) scale(-1, -1)");