svg - 无论 svg 的大小如何,都将元素放置在每个角上

标签 svg

我正在尝试创建一个每个角都有一个元素的 SVG。我希望 svg 是可缩放的,同时角元素保留其大小纵横比...同时坚持到角上。

我觉得只要摆弄大量的 JavaScript,就可以做到这一点。但我真的觉得这可以通过一些聪明的 css 和对 SVG 实际工作原理的良好理解来完成。

这是我期望它如何工作的示例:Demo Fiddle 。这只是 html 和 css。

div { width:40px; height:40px; position:absolute; 
  &:nth-of-type(1) { top:0; left:0; background-color:red;}
  &:nth-of-type(2) { top:0; right:0; background-color:blue;}
  &:nth-of-type(3) { bottom:0; left:0; background-color:green;}
  &:nth-of-type(4) { bottom:0; right:0; background-color:yellow;}
}

这是我最终来到这里之前到达的地方:Fiddle

<svg version="1.1" id="circle" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100"  xml:space="preserve" preserveAspectRatio="none">

  <svg id="top-left" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMinYMin meet">
    <rect width="20" height="20" fill="red" style="y:0; x:0"/>
  </svg>

  <svg id="top-right" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMaxYMin meet">
    <rect width="20" height="20" fill="blue" style="y:0; x:calc(100% - 20px)"/>
  </svg>

  <svg id="bottom-left" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMaxYMax meet">
    <rect width="20" height="20" fill="green" style="y:calc(100% - 20px); x:0"/>
  </svg>

  <svg id="bottom-right" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMinYMax meet">
    <rect width="20" height="20" fill="yellow" style="y:calc(100% - 20px); x:calc(100% - 20px)"/>
  </svg>  

</svg>

任何见解都将受到极大的赞赏。

干杯,

标记

最佳答案

如果角元素是对称的(从左到右和从上到下),那么您可以使用一些技巧,将右侧(或底部)元素放置在 x=-100%(或 y=-100)处%) 并应用 sx=-1(或 sy=-1)的缩放变换。

<svg x="0%" y="0%" width="100%" height="100%" style="border: 1px solid black;">
    <rect id="top-left" x="0%" y="0%" width="20" height="20" fill="red"/>
    <rect id="top-right" x="-100%" y="0%" width="20" height="20" fill="green" transform="scale(-1,1)"/>
    <rect id="bottom-left" x="0%" y="-100%" width="20" height="20" fill="blue" transform="scale(1,-1)"/>
    <rect id="bottom-right" x="-100%" y="-100%" width="20" height="20" fill="yellow" transform="scale(-1,-1)"/>
</svg>

请注意,此技巧仅适用于角元素对称的特殊情况。

关于svg - 无论 svg 的大小如何,都将元素放置在每个角上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36190523/

相关文章:

internet-explorer - IE中未保留带有空格的SVG文本元素

javascript - d3 - 单击时触发的拖动行为

javascript - SVG 投影分层

javascript - 依次绘制 D3 路径

java - 无法使 Batik 中的 JSVGCanvas 在 Maven 项目中工作

javascript - 允许 Raphael/SVG 元素事件通过顶部分层的 HTML 触发

javascript - 工具提示未显示在 d3 图表中点/圆顶部的附加 'rect' 处

html - 使用 "SVG polygon"悬停状态在 "SVG"之后淡入 div

java - JSVGCavas BridgeUserAgent displayError() 覆盖

html - 如何为导入 svg 图标的 md-icon 着色?