html - 图像未在 SVG arc (HTML) 中居中

标签 html svg

背景图片没有在我的 SVG 圆弧后面居中。你可以看到图像:here

我想要这样的东西:

here

显然没有红色切割部分。

我的HTML如下:

    <svg width="200" height="200">
    <defs>
        <pattern id="image"  x="0" y="0" width="1" height="1">
            <image x="0%" y="0%" width="100%" height="100%" xlink:href="Assets/Images/RoundSlider.png"></image>
        </pattern>
    </defs>
    <g transform="translate(100,100)" stroke="black" stroke-width="2">
        <path d="M 0 0 -70 70 A 99 99 0 1 0 -70 -70 Z" fill="url(#image)" />
    </g>
</svg>

最佳答案

发生这种情况是因为您的路径的边界框实际上比它是一个完整的圆圈时更多地从右侧开始:

const bbox = document.querySelector('path').getBBox();
const rect = document.querySelector('rect');
rect.setAttribute('x', bbox.x);
rect.setAttribute('y', bbox.y);
rect.setAttribute('width', bbox.width);
rect.setAttribute('height', bbox.height);
<h3>The red rectangle represents your &lt;path> BBox.</h3>
<svg width="200" height="200">
  <g transform="translate(100,100)" stroke="black" stroke-width="2" fill="none">
    <path d="M 0 0 -70 70 A 99 99 0 1 0 -70 -70 Z"/>
    <rect stroke="red"/>
    <circle stroke="green" r="100" cx="0" cy="0"/>
  </g>
</svg>

因此,您可以简单地调整图像的 x 属性,以便将此偏移量考虑在内(假设您有一张方形图像):

<svg width="200" height="200">
  <defs>
    <pattern id="image" width="1" height="1">
      <!--
        #mypath.getBBox().x = -70
        Add 100 from translate(100, 100)
        and we got our 30 units offset
      -->
      <image x="-30" y="0" width="200" height="200" xlink:href="https://upload.wikimedia.org/wikipedia/commons/9/95/Clock-green.png"/>
    </pattern>
  </defs>
  <g transform="translate(100,100)" stroke="red" stroke-width="2">
    <path id="mypath" d="M 0 0 -70 70 A 99 99 0 1 0 -70 -70 Z" fill="url(#image)"/>
  </g>
</svg>

或者您也可以只显示此 并对其进行剪辑(使用更复杂的路径可能会更容易):

<svg width="200" height="200">
  <defs>
    <clipPath id="myclip">
      <use xlink:href="#mypath"/>
    </clipPath>
  </defs>
  <image x="0" y="0" width="200" height="200" xlink:href="https://upload.wikimedia.org/wikipedia/commons/9/95/Clock-green.png" clip-path="url(#myclip)"/>
  <path id="mypath" d="M 0 0 -70 70 A 99 99 0 1 0 -70 -70 Z" fill="transparent" transform="translate(100,100)" stroke="red" stroke-width="2"/>
</svg>

关于html - 图像未在 SVG arc (HTML) 中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57138879/

相关文章:

javascript - 创建第二个 SVG 后,D3.js 不在第一个 SVG 上显示标签

html - CSS HTML 定位

html - 如何使网格中的图像填充 100% 的父元素?

javascript - 如何从现有的 svg 创建 img

javascript - 向第 3 方纯色圆环图添加渐变

javascript - 使用 Raphael.js 放在前面并发光

CSS SVG+XML - 如何编辑?

javascript - 验证不工作

html - 所有浏览器中的字体大小不一致

修复多个范围 slider 输入的 JavaScript 代码