How to remove black background using OpenCV grabcut in javascript?

I tried following the example in the docs for using grabcut but the result gives you the extracted foreground with black background. I’m trying to achieve the same output but with a transparent background.

I’ve seen some topics in the forum related to this but there aren’t any examples showing how to do it in Javascript. I have no knowledge of using C or Python yet, and I can’t figure out how to do this case from reading the docs.

This is the grabcut code from opencv.js documentation which I used.

let src = cv.imread('canvasInput');
cv.cvtColor(src, src, cv.COLOR_RGBA2RGB, 0);
let mask = new cv.Mat();
let bgdModel = new cv.Mat();
let fgdModel = new cv.Mat();
let rect = new cv.Rect(50, 50, 260, 280);
cv.grabCut(src, mask, rect, bgdModel, fgdModel, 1, cv.GC_INIT_WITH_RECT);
// draw foreground
for (let i = 0; i < src.rows; i++) {
    for (let j = 0; j < src.cols; j++) {
        if (mask.ucharPtr(i, j)[0] == 0 || mask.ucharPtr(i, j)[0] == 2) {
            src.ucharPtr(i, j)[0] = 0;
            src.ucharPtr(i, j)[1] = 0;
            src.ucharPtr(i, j)[2] = 0;
// draw grab rect
let color = new cv.Scalar(0, 0, 255);
let point1 = new cv.Point(rect.x, rect.y);
let point2 = new cv.Point(rect.x + rect.width, rect.y + rect.height);
cv.rectangle(src, point1, point2, color);
cv.imshow('canvasOutput', src);
src.delete(); mask.delete(); bgdModel.delete(); fgdModel.delete();

Can anyone help with this?