Search code examples
svgblazor-client-side

Blazor - Add element to SVG object


I want to manipulate an SVG object with blazor, is it possible to do this via C# client side, or do I need to use javascript. For example, draw a line programatically based on clicks in the SVG area. Any pointers would be greatly appreciated. I found a lot on adding SVG component, but nothing on adding elements to the already existing svg component


Solution

  • You can use SVG file contents as the markup in a Blazor component, and then do any of the Blazor-y things you'd normally do.

    Put a variable in the svg markup, and build it as a string.

    Here's a highly-simplified excerpt: (MySvgComponent.blazor)

    <svg blah blah blah>
        <polyline fill="none" stroke="#0074d9"
            stroke-width="2" points="@PointString" />
    </svg>
    @code {
        public string @PointString {get;set;}
        public void AddPoint (int X, int Y){
             @PointString += " " + X + "," + Y;
    }
    

    You'll have to add your own code to figure out where you want to add the points. You could make a List<Point> parameter to pass in from a parent or something, and then call AddPoint in a foreach loop in OnInitialized(). You could also very easily replace the stroke color or anything else by replacing literals like "0074d9" with variables "@myColorString."

    Handling mouse-click locations will require some fancy JS work. Try using Javascript Interop with something like the following: How to get the click coordinates relative to SVG element holding the onclick listener?