Currently I have tweaked the code base as follows:
Expose the Id property on the BECanvas component as public:
public readonly string Id = Guid.NewGuid().ToString();
Include a TypeScript file with an interop function:
declare namespace BlazorExtensions {
class Canvas2d {
static getContext(canvas: { id }): CanvasRenderingContext2D;
}
}
// canvas: HTMLCanvasElement
function drawPixels(id: number, x: number, y: number, xw: number, yw: number, pixels: Uint8Array) {
let ctx = BlazorExtensions.Canvas2d.getContext({
id : id
});
const imageData = ctx.createImageData(xw, yw);
// Iterate through every pixel
for (let i = 0; i < imageData.data.length; i += 4) {
// Modify pixel data
imageData.data[i + 0] = pixels[i]; // R value
imageData.data[i + 1] = pixels[i + 1]; // G value
imageData.data[i + 2] = pixels[i + 2]; // B value
imageData.data[i + 3] = pixels[i + 3]; // A value
}
// Draw image data to the canvas
ctx.putImageData(imageData, x, y);
}
Call the interop function from my Blazor component:
uint[] byteArray = new uint[100 * 100 * 4];
var idx = 0;
for (int y = 0; y < 100; y++)
for (int x = 0; x < 100; x++)
{
byteArray[idx] = 128; // R
byteArray[idx + 1] = 200; // G
byteArray[idx + 2] = 60; // B
byteArray[idx + 3] = 255; // A
idx += 4;
}
var text =
await JSRuntime.InvokeAsync("drawPixels", _canvasReference.Id, 0, 0, 100, 100, byteArray);
I would love to have support for putImageData.
Currently I have tweaked the code base as follows:
Expose the Id property on the BECanvas component as public:
public readonly string Id = Guid.NewGuid().ToString();
Include a TypeScript file with an interop function:
Call the interop function from my Blazor component:
var idx = 0; for (int y = 0; y < 100; y++) for (int x = 0; x < 100; x++) { byteArray[idx] = 128; // R byteArray[idx + 1] = 200; // G byteArray[idx + 2] = 60; // B byteArray[idx + 3] = 255; // A idx += 4; }
var text = await JSRuntime.InvokeAsync("drawPixels", _canvasReference.Id, 0, 0, 100, 100, byteArray);