【问题标题】:SVG elements rendering in blazor using JSInterop使用 JSInterop 在 blazor 中渲染 SVG 元素
【发布时间】:2020-07-28 05:59:34
【问题描述】:

我需要在 blazor 的 svg 中渲染文本元素、线条元素等。所以,我创建了一个 jSinterop 来执行这些操作,这样我就可以在任何需要的地方调用 js 方法。 我的代码sn-p,

.razor

@inject IJSRuntime JsInterop

<svg id="parentElement">
    @for (var i = 0; i < count; i++)
    {
        @RenderTextElements()
    }
    </svg>

@code { 
int count = 10;
public object RenderTextElements()
{
    return (JsInterop.InvokeAsync<object>("elementText", new object[] { }));
}}

我的js文件是

window.elementText = function () {
    var svgElement = this.document.getElementById('parentElement');
    var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');   
    text.setAttribute('fill', 'black');
    text.textContent = 'hello world';
    svgElement.insertAdjacentElement('afterbegin', text)
}

调用了这个 js 方法,但是文本元素没有附加到 DOM。 当我通过这种方法进行调试时,我可以看到附加到 DOM 的元素。后来,它被删除。我找不到它被删除的位置。

【问题讨论】:

  • 究竟为什么需要 JS?你不能只用 C#/Blazor 生成元素吗?
  • 是的,我也可以在 blazor 中生成元素。只是我需要使用 blazor 和 JS 检查 svg 渲染的性能。所以我是这样检查的。

标签: c# svg blazor


【解决方案1】:

在 svg 中,您必须设置元素的位置:

  <script>

    function insertElements() {
      let parent = document.getElementById("parent");

      for (let i = 0; i < 5; i++) {
        let text = document.createElementNS('http://www.w3.org/2000/svg', "text");
        text.setAttribute("x", 10);
        text.setAttribute("y", 10 + 15 * i);
        text.style.fill = "blue";
        text.textContent = "text " + i;
        parent.insertAdjacentElement("afterbegin", text);
      }

    }

    function test() {
      insertElements();
    }

  </script>
</head>
<body>

  <button onclick="test()">Test</button>
  <svg id="parent" width="200" height="200">
  </svg>

</body>

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 2018-05-08
    • 2022-01-19
    相关资源
    最近更新 更多