To use HTML5 Canvas in Blazor, you can follow these steps:
1.Add the necessary HTML markup for the Canvas element in your Blazor component. For example:
<canvas id="myCanvas"></canvas>
Here’s an example of using HTML5 Canvas in a Blazor component:
[Index.razor]
@page "/"
@inject IJSRuntime JSRuntime
<h1>Canvas Demo</h1>
<canvas id="myCanvas"></canvas>
@code {
protected override async Task OnAfterRenderAsync ( bool firstRender )
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("canvasInterop.setupCanvas");
}
}
}
2.Add the following script source to [_Host.cshtml/_Layout.cshtml/index.html].
<script>
window.canvasInterop = {
setupCanvas: function () {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Perform various operations on the canvas using the context object
// Example: Draw a rectangle
context.fillStyle = "red";
context.fillRect(10, 10, 100, 100);
}
};
</script>
Share with