Live Chat Icon For mobile
Live Chat Icon

How do you use HTML5 Canvas in Blazor?

Platform: Blazor| Category : General, Components

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: 

@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]. 

    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); 

Share with

Related FAQs

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

Please submit your question and answer.