Home > Back-end >  How do I exclude canvas element from Blazor Server page when modifying DOM from js?
How do I exclude canvas element from Blazor Server page when modifying DOM from js?

Time:02-05

I have a canvas tag which I update only using js logic. But after the first update, the canvas element is moved to the bottom of the html tree (guess it's a razor's fallback strategy when DOM is changed outside and it internal representation doesn't match). It would be nice to use something like:

@excludeFromRender { <canvas id="myCanvas"></canvas> }

What options do I have to update canvas element in the middle of page from js (meaning client-side) and keep it in right place of page? I should note that it's mandatory to use Blazor Server.

I don't know how to make it work.

CodePudding user response:

I'm not sure why the element would be moved to the bottom of the tree.

Here's a simple wrapper component to do your excludeFromRender. It only renders once when the page loads:

    public sealed class RenderOnce : IComponent
    {
        private RenderFragment _renderFragment;
        private RenderHandle _renderHandle;
        private bool _hasNeverRendered = true;

        [Parameter] public RenderFragment? ChildContent { get; set; }

        public RenderOnce()
        {
            _renderFragment = builder =>
            {
                _hasNeverRendered = false;
                builder.AddContent(0, ChildContent);
            };
        }

        public void Attach(RenderHandle renderHandle)
            => _renderHandle = renderHandle;

        public Task SetParametersAsync(ParameterView parameters)
        {
            parameters.SetParameterProperties(this);
            if (_hasNeverRendered)
                _renderHandle.Render(_renderFragment);
            return Task.CompletedTask;
        }
    }

Then use it like this:

<RenderOnce>
 <canvas id="myCanvas"></canvas>
</RenderOnce>

CodePudding user response:

So, I figured what was wrong in my case. I simply forgot to remove document.body.appendChild(canvas); at the end of canvas update logic. Sorry to bother.

  • Related