Hot to get key events for Blazor.Extensions.Canvas

Viewed 822

I enjoy writing my very first Blazor app. I want to move 2D graphics on a canvas, I'm using the Blazor.Extensions.Canvas assembly. Unfortunately I'm not able to get key events from the canvas.

@page "/pacman"

<BECanvas Width="800" Height="600" @ref="_canvasReference" @onkeypress="KeyWasPressed"/>


@code {

    private Canvas2DContext _context;
    protected BECanvasComponent _canvasReference;

    private int _xPos = 10;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        _context = await _canvasReference.CreateCanvas2DAsync();
        await _context.SetFillStyleAsync("green");
        await _context.FillRectAsync(_xPos, 100, 100, 100);
    }

    private void KeyWasPressed(KeyboardEventArgs e)
    {
        _xPos += 10;
    }
}

This approach does not work, the green rect is not moving to the right when I press any key. I'm using dotnet 3.1.102 and Blazor.Extensions.Canvas Release v1.1.0-preview1.

Does anybody know how I can get the key events to move my rectangle?

1 Answers

The basic solution is

<div tabindex="0" @onkeydown="KeyWasPressed">
    <BECanvas  Width="800" Height="600" @ref="_canvasReference"  />
</div>

and then you may have to click in the Canvas once, depending on how you set up the Main page and NavMenu.

Making sure the Canvas (-div-page) has the focus is something to configure separately .

Related