Reputation: 895
I need to render text elements, line elements, etc in the svg in blazor. So, I have created a jSinterop to perform this operations so that I can call the js methods wherever it is necessary. My code snippet,
.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[] { }));
}}
My js files is
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)
}
This js method is invoked but text element did not append to DOM. When I debugging through this method, I can see the element appended to DOM. Later, it is removed. I can't find where it is removed.
Upvotes: 2
Views: 874
Reputation:
In svg you'll have to set the position for an element:
<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>
Upvotes: 1