BlazorExtensions / Canvas

HTML5 Canvas API implementation for Microsoft Blazor
MIT License
620 stars 144 forks source link

How to use drawImage on 2D Canvas using many server side dynamic images. #45

Open equinox2k opened 5 years ago

equinox2k commented 5 years ago

I understand normally you would have a HTMLImageElement with an element reference and would use drawImage that way, however in my case I have many dynamically created Image server side and wondering if its possible some how to pass in say base64encoded image instead from server side.

MarkH170 commented 4 years ago

We did this using the following JsInterop code, it might be something to add through a pull request here but I didn't have the time yet.

JsInterop:

DrawBackgroundImage(canvas, imgUrl, dx, dy, dw, dh) {
        return new Promise(resolve => {
            let ctx = canvas.getContext('2d');

            let img = new Image();
            img.onload = () => {
                ctx.drawImage(img, dx, dy, dw, dh);
                return resolve("Finished");
            };

            img.src = imgUrl;
        });
    },

File bundling all our JsInterop calls:

public async Task<string> DrawBackground(ElementReference canvas, string url, double dx, double dy, double dw, double dh) {
            return await jsRuntime.InvokeAsync<string>("CanvasComponent.DrawBackgroundImage", canvas, url, dx, dy, dw, dh);
        }

Call to our bundle file, canvas is of type ElementReference here. You can access this by using the Canvas2DContext.Canvas property.

The URL is the actual image location, something like: "img/components/background.png" in our case.

return await bundledJsInterop.DrawBackground(canvas, url, dx, dy, dwidth, dheight);