Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the HTML Canvas from Blazor?

Tags:

blazor

I am trying to do 2D drawing to the HTML Canvas from Blazor. I tried using the Blazor.Extensions.Canvas but it seems to be quite dated and targeted at a prior Blazor Server Side implementation.

I tried implementing a simple example and got an exception

with...

{
protected Blazor.Extensions.BECanvasComponent _canvasRef;
private Blazor.Extensions.Canvas.Canvas2D.Canvas2DContext _context;

// Note I had to provide the full path since it seemed to ignore
//  my @using statement in most cases

    protected override async Task OnAfterRenderAsync()
    {
      this._context = await this._canvasRef.CreateCanvas2DAsync();
      await this._context.SetFillStyleAsync("green");

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

      await this._context.SetFontAsync("48px serif");
      await this._context.StrokeTextAsync("Hello Blazor!!!", 10, 100);
    }
}

I even had to add the full path for the canvas classes in the generated files. However, I finally got it to build without warnings. I expected it to draw the green filled rectangle but ...

This created an 'unhandled exception rendering component ' in the browser: 'Microsoft.JSInterop.JSException: t.getContext is not a function'

referencing the line: ' this._context = await this._canvasRef.CreateCanvas2DAsync();'

like image 209
David Bowser Avatar asked Nov 06 '22 15:11

David Bowser


1 Answers

I believe the problem in compatibility of .net core version and canvas version. (I had same problems with .net core preview 6 and canvas 0.1.9). Currently they released Canvas 0.2.0, so it should work with .core preview 7.

like image 162
Maksim Avatar answered Nov 26 '22 05:11

Maksim