Search code examples
javascriptarraysreactjscanvasbase64url

Uint clamped array to data url


I want to get part of a canvas in the base 64 data url format which will be sent to my api for this is I am using the ctx.getImageData() method which is returning a clamped uint 8 array here is the code:

        const data = ctx.getImageData(mousex, mousey, mousex1, mousey1);
        const clamped = data.data
}

I have tried many btoa methods but the either return a broken array full of A or a broken array with a lot of /


Solution

  • You can use canvas.toDataURL(type, encoderOptions) for this purpose.

    1. First extract the part of your source image. You don't need getImageData() for that. Instead create a second canvas with part_canvas = document.createElement("canvas"), this canvas doesnt have to be visible on the page.
    2. Assign it its size .width and .height of the part you want to extract
    3. part_ctx = part_canvas.getContext("2d") on the canvas
    4. Then part_ctx.drawImage(source_image, part_x, part_x, part_width, parth_height, 0, 0, part_width, parth_height); This will take a rectangualr area of the source image and put it in the invisble canvas.
    5. Finally you can do part_canvas.toDataURL() and you have the data URL

    Didn't test. But I think this should work.