【问题标题】:SVG: Why aren't the shapes drawn inside svg visible which is on an image?SVG:为什么在图像上的 svg 中绘制的形状不可见?
【发布时间】:2021-06-01 21:42:40
【问题描述】:

我正在与 Angular 合作。我的目标是在图像中绘制多边形。为此,我在图像中放置了一个 svg。 img 和 svg 具有宽度和高度,并且多边形的点在数据库中,因此它们的值不能改变。问题是多边形显示不好。这是一个小例子:

这是我的代码:

HTML:

<div class="img-map">
    <img #image src="https://content.gnoss.ws/imagenes/Documentos/ImagenesSemanticas/07aabdfa-981f-41f7-828d-78f21adb80a6/eb1d0185-7d5b-4d3a-b84a-5aefd95d3365.jpg" alt=""/>

    <svg style="position:absolute; left:0px; top:0px; width: 100%; height: 100%">
        <polygon class="polygonStyle" [attr.points]="stringPoints" />
    </svg>

</div>

CSS:

.img-map {
  overflow: auto;
  position: relative;
  max-width: calc(100vw - 450px);
}

.polygonStyle {
  stroke: rgba(0, 0, 255, 0.75);
  fill: none;
}

img {
  top: 0;
  left: 0;
  border-radius: 10px;
  height: auto;
  width: 100%;
}

TS:

stringPoints = "1015,481 1043,578 1087,565 1055,467";

我已经完成了stackblitz。我想这个问题与规模有关,但我不知道如何解决。

我的尝试:

  • 我在 stackoverflow 中看到了这个 question,但我没有看到任何有效的答案。
  • 这个proyect 包含带有viewbox 属性的代码,但它没有任何作用。

我不知道我做错了什么。谢谢!

【问题讨论】:

  • 您是否尝试将position: absolute 放在position: relative 的子元素中?
  • @efkah 是的,它实际上在我编写的代码中。 svg 有position:absolute.
  • 图片没有宽高。此外,您将需要 svg 具有与图像相同的宽度和高度,但这一切都取决于数据库中的坐标。这些坐标看起来如何:百分比?只是数字?另外:如果您需要响应式图形,您可能需要 svg 元素的 viewBox 属性。
  • @enxaneta 它们在数据库中的存储方式并不重要,因为我将它们的格式转换为多边形所需的字符串。所以,stringPoints 变量很重要

标签: angular typescript svg


【解决方案1】:

SVG 的默认视图框为 300 x 150,原点为 0,0。在您的示例中,多边形坐标为:1015,481 1043,578 1087,565 1055,467。所以它们都在 SVG 的可见区域之外。因此,什么都看不见。

你应该设置一个显式视图框,例如:

<svg viewBox="1000 400 100 200" style="position:absolute; left:0px; top:0px; width: 100%; height: 100%">
    <polygon class="polygonStyle" [attr.points]="stringPoints" />
</svg>

它设置了一个原点为 1000,400 且大小为 100 x 200 的视图框。然后您的 SVG 内容将被平移和缩放,以使所有坐标的 x 位置在 1000 到 1100 之间以及 y 位置400 到 600 之间位于 SVG 的可见区域内。

所以viewBox 属性会影响SVG 的内容。另一边的widthheightposition 不会影响 SVG 的内容,而是会影响 SVG 的显示位置和大小。

【讨论】:

  • 是的。你说得对。我会将答案标记为正确。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 2020-03-23
  • 1970-01-01
  • 2010-12-27
相关资源
最近更新 更多