我对svg文件有问题。我已经将svg文件放入img中的src中
SVG loader.svg:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: none; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
<circle cx="50" cy="50" fill="none" stroke="#000" stroke-width="4" r="17" stroke-dasharray="80.11061266653974 28.703537555513243" transform="rotate(46.7215 50 50)">
<animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform>
</circle>
</svg>
HTML中的img
<img src="loader.svg" />
loader img此加载程序的宽度为:200px,高度为:200px,圆圈内部宽度为:100px,高度为:100px。不幸的是,当我更改img圆的大小时,里面的大小也会更改,因为整个svg大小都会更改。
我想得到结果:要在svg中固定大小的圆圈-可以更改背景的大小,但圆圈insiede始终应为100x100px。
是否可以在svg中修复此大小?
因为您的viewBox始终是100x100的网格(不是像素!),如果您以另一比例显示SVG 它会拉伸SVG向量
要维持50个PIXEL RADIUS圆,您必须动态更改Circle SVG。
[经验丰富的SVGer可以通过使用矩阵变换圆的刻度来做到这一点
更容易为您的圆计算3个参数:
RADIUS,还有STROKEWIDTH(在每个实例中保持相同的宽度)和GAP(周长的25%)
((并以一个百分比将圆心居中!)
<circle cx="50%" cy="50%" stroke-width="STROKEWIDTH" r="RADIUS" stroke-dasharray="GAP">
最容易将JavaScript包装在现代W3C标准自定义元素中,因此您可以使用语义HTML:
<svg-loader width=6 color=red id=loader_1></svg-loader>
<svg-loader width=6 color=blue id=loader_2></svg-loader>
<svg-loader width=6 color=green id=loader_3></svg-loader>
<template id="SVG-LOADER">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50%" cy="50%" fill="none" stroke="COLOR" stroke-width="STROKEWIDTH" r="RADIUS" stroke-dasharray="GAP" transform="rotate(0 50 50)">
<animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform>
</circle>
</svg>
</template>
<script>
customElements.define('svg-loader', class extends HTMLElement {
connectedCallback() {
let svgTemplate = document.getElementById(this.nodeName).innerHTML;
this.hostIMG = this.appendChild(document.createElement("IMG"));
let { width } = getComputedStyle(this.hostIMG);
width = Number(width.replace(/px/, ''));
if (width === 0) width = 100;
let strokewidth = Number(this.getAttribute("width"));
let radius = (100 / width * (50 - (strokewidth / 2)));
let gap = 2 * 3.14 * radius * 3 / 4; //25% gap
strokewidth = (100 / width * strokewidth)
this.hostIMG.src = `data:image/svg+xml,` +
svgTemplate.replace(/"/g, "'").replace(/#/g, "%23")
.replace(/RADIUS/g, radius).replace(/STROKEWIDTH/g, strokewidth)
.replace(/GAP/g, gap).replace(/COLOR/g, this.getAttribute("color"));
}
});
</script>
<style>
svg-loader img { background: lightblue; }
#loader_1 img { width: 100px; }
#loader_2 img { width: 175px; }
#loader_3 img { width: 80px; }
</style>
<svg-loader width=6 color=red id=loader_1></svg-loader>
<svg-loader width=6 color=blue id=loader_2></svg-loader>
<svg-loader width=6 color=green id=loader_3></svg-loader>