gpt4 book ai didi

javascript - 如何使用 JavaScript 使 SVG 缩放到父容器的全高和全宽?

转载 作者:行者123 更新时间:2023-11-28 01:56:45 26 4
gpt4 key购买 nike

我有一个棒球场的 SVG,我试图通过其父容器的属性设置它的宽度和高度。

这是我的 fiddle :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 未定义。我也知道我需要设置视口(viewport)。

我之前也检查过这个: How can I make an svg scale with its parent container?

最佳答案

您链接到的 SVG 有一个固定的 widthheight (650 x 500),因此您将无法按照现在的方式进行操作(即通过 <object>

你有两个选择:

  1. 将 SVG 复制到本地并进行修改。添加 viewBox属性并更改 widthheight"100%" .

    <svg ... width="100%" height="100%" viewBox="0 0 650 500" ... >
  2. 另一种解决方案是将 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;
    }

    https://jsfiddle.net/a5mz90jy/12/

关于javascript - 如何使用 JavaScript 使 SVG 缩放到父容器的全高和全宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com