包括一个SVG文件并改变它的高度


Including an SVG file and changing it's height

我有一个SVG文件,我想包括使用php include 'svg/file.svg';的事情是,我希望能够设置SVG的高度,当我包括它

所以我想写一个函数:

function importSVG($file, $height) {
    $svg = file_get_contents($file);
    // magic to set height?
    return $svg;
}

然而,我不知道如何设置一个高度属性。我可能会在每页使用这个函数20-30次。所以我不想正则化整个SVG代码,因为有些SVG文件很大。

SVG文件示例:

<svg><path d="M.524 7.42C-.318 8.846.342 10 2 10h7c1.657 0 2.317-1.156 1.476-2.58L6.516.72c-.56-.95-1.473-.947-2.032 0l-3.96 6.7z"></path></svg>

您可以避免修改SVG,而且如果使用符号技术,您只需要在页面中包含它一次。

确保您的SVG有一个viewBox,并将其转换为如下的符号:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
  <symbol id="my-icon" viewBox="0 0 100 100">
    <!-- <path>s and whatever other shapes in here -->  
  </symbol>
</svg>

然后当你需要使用它时,在你的页面中添加以下内容:

<svg class="icon-small">
  <use xlink:href="#my-icon" />
</svg>

类定义为:

.icon-small {
  width: 32px;
  height: 32px;
}

如果你需要一个更大的版本,你可以这样做:

<svg class="icon-large">
  <use xlink:href="#my-icon" />
</svg>
.icon-large {
  width: 48px;
  height: 48px;
}

.icon-small {
    width: 32px;
    height: 32px;
}
    
.icon-large {
    width: 48px;
    height: 48px;
}
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
      
    <symbol id="my-icon" viewBox="0 0 100 100">
       <circle cx="50" cy="50" r="45" fill="blueviolet" stroke="orange" stroke-width="6"/>
    </symbol>
      
</svg>
<h1> Example </h1>
<svg class="icon-small">
  <use xlink:href="#my-icon" />
</svg>
<svg class="icon-large">
  <use xlink:href="#my-icon" />
</svg>