简体   繁体   中英

Generating circles dynamically in Blazor using C#

I will be pulling few numbers from the database and once pulled I want to generate circles around the numbers and size the circles based on the numbers. This means circle with 140 will be bigger than circle with 120, circle with 60 will be smaller than circe with 120

I will be using Blazor and C# to develop this. How can I go about it? I am new to Blazor. The circles should also be draggable.

在此处输入图像描述

Get ready to have your mind blown. All modern browsers support inline SVG. And Blazor is the absolute perfect platform to interact with SVG elements using variables. You can literally make entire components using no HTML.

Note that since SVG is not pixel-based, your graphics will scale as big as a building and will still have nice clean lines. Try a value of 1000 to see what I mean.

Circle.razor

@page "/circle"

<h3>Circle Size</h3>
<div>
    <input type="number" @bind="@radius" step="10" />
    <button @onclick="Flash">Flash!</button>
</div>
<svg height="@(radius*2)" width="@(radius*2)">
    <circle cx="@radius" cy="@radius" r="@(radius*0.8)" stroke="black" stroke-width="@(radius *0.05)" fill="@color" />
    <text x="50%" y="50%" text-anchor="middle" alignment-baseline="central" fill="#fff" font-size="@(radius*0.6)px">@radius</text>
</svg>


@code {
    int radius {get; set;} = 100;
    string color { get; set; } = "#a0a";
    async Task Flash()
    {
        var random = new Random();
        for (int i=1; i<20; i++)
        {
            color = String.Format("#{0:X6}", random.Next(0x1000000));
            await Task.Delay(10);
            StateHasChanged();
        }
    }
}

By the way most SVG properties can be animated for extra bling: color shifts, sizes, position, rotation, anything you want.

Here's an answer showing how to use Circle as a component.

Circle.razor

<svg height="@(radius*2)" width="@(radius*2)">
    <circle cx="@radius" cy="@radius" r="@(radius*0.8)" stroke="black" stroke-width="@(radius *0.05)" fill="#a0a" />
    <text x="50%" y="50%" text-anchor="middle" alignment-baseline="central" fill="#fff" font-size="@(radius*0.3)px">@displayValue</text>
</svg>


@code {
    [Parameter]
    public int radius {get; set;}

    [Parameter]
    public string displayValue { get; set; }
}

ParentPage.razor

@page "/"
@page "/circles"

<h3>Circles</h3>

@foreach (int value in Values)
{
    <Circle radius="value" displayValue="@("pop. " + value)" />
}

@code {
    List<int> Values = new List<int> { 100, 230, 300, 75 }; 
    // You'll have to come up with your own list of values however you want.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM