也许是这样的:
function cloneWithTransformedAttributes(obj1, mapping) {
// returns copy of obj1 with child node attributes transformed according to mapping.
const obj2 = obj1.cloneNode(true);
[...obj1.children].forEach((child, idx)=>{
Object.keys(mapping).forEach((attribute) => {
const replacementVal = mapping[attribute].default ?
mapping[attribute].default :
child.getAttribute(mapping[attribute]);
obj2.children[idx].setAttribute(attribute, replacementVal);
})
})
return obj2;
}
mapping = {
x: {
default: 0
},
y: "x",
width: "height",
height: "width"
}
const verticalSvg = document.getElementsByTagName("svg")[0];
const horizontalSvg = cloneWithTransformedAttributes(verticalSvg, mapping);
const graphs = document.getElementById("graphs");
graphs.appendChild(horizontalSvg);
<style>
svg { height: 20px; width: 100px; border: 1px solid #ccc;}
</style>
<div id="graphs">
<svg>
<rect x="5%" y="60%" width="40%" height="40%" fill="black"/>
<rect x="55%" y="40%" width="40%" height="60%" fill="black"/>
</svg>
</div>
编辑:您也可以使用 svg 转换来做到这一点,但您需要将 SVG 的内部放在一个 group<g></g>
中。这是一个手动计算转换和 JS 解决方案的示例,该解决方案通过获取原始 svg 宽度和高度来自行计算转换:
const verticalSvg = document.getElementsByTagName("svg")[0];
const svgStyle = window.getComputedStyle(verticalSvg, null);
const width = parseInt(svgStyle.getPropertyValue("width"));
const height = parseInt(svgStyle.getPropertyValue("height"));
const whRatio = width / height;
const transform = `rotate(90) scale(${1 / whRatio} ${whRatio}) translate(0 -${height})`
const horizontalSvg = verticalSvg.cloneNode(true);
horizontalSvg.children[0].setAttribute("transform", transform);
const graphs = document.getElementById("graphs");
graphs.appendChild(horizontalSvg);
<style>
svg { height: 20px; width: 100px; border: 1px solid #ccc; overflow: visible}
</style>
<div id="graphs">
<svg>
<g>
<rect x="5%" y="60%" width="40%" height="40%" fill="black"/>
<rect x="55%" y="40%" width="40%" height="60%" fill="black"/>
</g>
</svg>
<svg>
<!-- Manually calculated and applied transform -->
<g transform="rotate(90)
scale(0.20 5)
translate(0 -20)
">
<rect x="5%" y="60%" width="40%" height="40%" fill="black"/>
<rect x="55%" y="40%" width="40%" height="60%" fill="black"/>
</g>
</svg>
<!-- JS generated SVG will get inserted here -->
</div>
在您的情况下,您需要将转换应用于保存 SVG 内容的组。如果将变换应用于 SVG 本身,它还将根据缩放变换缩放边框。
vector-effect="non-scaling-stroke"
不能应用于不属于 SVG 本身的 SVG 的边框。但是,如果您在 SVG 中使用具有“stroke”属性的元素,那么您可能还希望将vector-effect="non-scaling-stroke"
属性应用到它们。