I'm trying to build a rudimentary paint app using Blazor Wasm as a learning exercise. Drawing to the canvas through the API provided by Blazor.Extensions.Canvas seems to work fine, but I'm trying to save the contents of the canvas to a PNG and I'm running into issues. Since there is no method for this in the C# wrapper that Blazor.Extensions.Canvas provides, I have a simple JS function inside a script tag in index.html:
function saveCanvasContents(canvcont) //this parameter is supposed to be the canvas context object
{
return canvcont.toDataURL();
}
Which is being called from the C# component like this:
Object testObject = await jsRuntime.InvokeAsync<Object>("saveCanvasContents", new object[] {_context});
_context here is the Blazor Extensions Canvas' context, which is generated in OnAfterRenderAsync by _context = await CanvasReference.CreateCanvas2DAsync();.
Anyway, running this produces Microsoft.JSInterop.JSException: canvcont.toDataURL is not a function in the browser console. My intuition here would be that this is because whatever I'm passing it isn't a HTMLCanvasElement and as such doesn't have a toDataURL. Passing it the reference to the canvas component (CanvasReference above, it's of type BECanvasComponent) has the same result. Am I misunderstanding something fundamental about Blazor's JS interop / JS in general, or is there a better way of going about this in Blazor?
Figured it out. I had to pass the method my _context.Canvas. Everything else I passed it was referring to a BECanvas component, which wraps an HTML5 canvas, rather than a regular old HTML canvas, so it would make sense that one of those doesn't have a toDataURL method. Good luck to anyone finding this in the future.