Live Chat Icon For mobile
Live Chat Icon

How do you use Canvas in Blazor?

Platform: Blazor| Category : General, Components

Currently there is no direct Canvas support in WebAssembly. In order to draw using Canvas, you can use the third-party, free Blazor.Extensions.Canvas library. Add Blazor.Extensions.Canvas NuGet to your project and add the following code snippet to draw a rectangle. It draws shapes in Blazor with the reference that is created for the Canvas element in the Razor page.

[index.html/_host.cshtml]
<head>

 <script src="_content/Blazor.Extensions.Canvas/blazor.extensions.canvas.js"></script>

</head>
[index.razor]

@page "/"
@using Blazor.Extensions; 
@using Blazor.Extensions.Canvas
@using Blazor.Extensions.Canvas.Canvas2D;

<BECanvas Width="300" Height="400" @ref="_canvasReference"></BECanvas>

@code {
    private Canvas2DContext _context;

    protected BECanvasComponent _canvasReference;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        this._context = await this._canvasReference.CreateCanvas2DAsync();
        await this._context.SetFillStyleAsync("red");

        await this._context.FillRectAsync(10, 100, 100, 100);

        await this._context.SetFontAsync("38px Calibri");
        await this._context.StrokeTextAsync("Hello Blazor!!!", 5, 100);
 }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.