Blazor-Canvas
[删除(380066935@qq.com或微信通知)]
Canvas
BlazorExtensions/Canvas: HTML5 Canvas API implementation for Microsoft Blazor (github.com)
HTML5 Canvas API implementation for Microsoft Blazor
Blazor Extensions
Blazor Extensions are a set of packages with the goal of adding useful things to Blazor.
Blazor Extensions Canvas
This package wraps HTML5 Canvas APIs.
Both Canvas 2D and WebGL are supported.
Both Blazor Server Apps and Blazor WebAssembly Apps are supported.
NOTE Currently targets the v3.1.5 of Blazor with 3.2.0 of WebAssembly
Installation
Install-Package Blazor.Extensions.Canvas
Sample
Usage
In your index.html
file (WebAssembly Apps) or _Host.cshtml
(Server Apps) file, place a reference to the library's script file:
<script src="_content/Blazor.Extensions.Canvas/blazor.extensions.canvas.js"></script>
In your _Imports.razor
add the following using
entry:
@using Blazor.Extensions.Canvas
In the component where you want to place a canvas element, add a BECanvas
. Make sure to set the ref
to a field on your component:
<BECanvas Width="300" Height="400" @ref="_canvasReference" ></BECanvas>
2D
In your component C# code (regardless if inline on .razor or in a .cs file), add a BECanvasComponent
reference which matches the ref
you set on your BECanvas
.
Create a Canvas2DContext
, and then use the context methods to draw on the canvas:
private Canvas2DContext _context;
protected BECanvasComponent _canvasReference;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
this._context = await this._canvasReference.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);
}
NOTE You cannot call CreateCanvas2DAsync
in OnInitAsync
, because the underlying <canvas>
element is not yet present in the generated markup.
WebGL
In your component C# code (regardless if inline on .razor or in a .cs file), add a BECanvasComponent
reference which matches the ref
you set on your BECanvas
.
Create a WebGLContext
, and then use the context methods to draw on the canvas:
private WebGLContext _context;
protected BECanvasComponent _canvasReference;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
this._context = await this._canvasReference.CreateWebGLAsync();
await this._context.ClearColorAsync(0, 0, 0, 1);
await this._context.ClearAsync(BufferBits.COLOR_BUFFER_BIT);
}
NOTE You cannot call CreateWebGLAsync
in OnInitAsync
, because the underlying <canvas>
element is not yet present in the generated markup.