[英]How to give a fixed height and width to SVG text element using javascript?
[英]How to get SVG to scale to full height and width of parent container using JavaScript?
我有一个SVG棒球钻石,我正尝试通过其父容器的属性设置其宽度和高度。
这是我的小提琴: https : //jsfiddle.net/a5mz90jy/6/
这是我的Javascript:
const svgBaseballField = document.getElementById('diamond');
console.log(svgBaseballField);
const svgContainer = document.getElementsByClassName('svg_container');
console.log(svgContainer);
const svgContainerHeight = svgContainer.clientHeight;
console.log(svgContainerHeight);
const svgContainerWidth = svgContainer.clientWidth;
svgBaseballField.setAttribute("width", svgContainerWidth);
svgBaseballField.setAttribute("height", svgContainerHeight);
svgBaseballField.setAttribute("viewBox", "0 0 100 100");
我知道有些问题,因为svgContainerHeight和svgContainerWidth是未定义的。 我也知道我需要将视口设置为某种东西。
我之前也进行了检查: 如何使用其父容器制作svg刻度?
您要链接的SVG具有固定的width
和height
(650 x 500),因此您将无法以现在的方式(例如,通过<object>
。
您有两种选择:
在本地复制SVG并进行修改。 添加viewBox
属性,并将width
和height
更改为"100%"
。
<svg ... width="100%" height="100%" viewBox="0 0 650 500" ... >
另一个解决方案是将SVG包含为背景图像,并利用CSS背景大小调整属性。
.svg_container { width: 75%; height: 100%; background: url(https://upload.wikimedia.org/wikipedia/commons/8/89/Baseball_diamond_clean.svg) blue; background-repeat: no-repeat; background-size: contain; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.