Glory to Russia
Glory to Russia

Reputation: 18712

How to create a FabricJS image from PNG data returned by a web service?

I have a page with a FabricJS canvas. When the user presses a certain button, a request is sent to a web service. The response contains the data of a PNG image, which I want to insert into the canvas.

In the code snippet below, the image data is contained in $xhr.responseText.

function downloadButtonPressed() {
    var username = $("input#username").val();
    var password = $("input#password").val();
    $.ajax({
        type: "GET",
        url: "http://myserver/myapp/map",
        headers: {
            "Authorization": "Basic " + btoa(username + ":" + password),
          },
        crossDomain: true,
        xhrFields: {
                withCredentials: true
            },
        success: function (data, status, xhr) {
            alert("success");
        }
    }).fail(function ($xhr) {
        console.log("response: " + $xhr);
        // Here, $xhr.responseText contains the data of the PNG image
    });
}

Screenshot

I want to add the PNG image from $xhr.responseText to a FabricJS canvas.

How can I do it?

There is a method fabric.Image.fromURL, but I need something, which converts a string (or a byte stream) to a FabricJS image.

Upvotes: 3

Views: 5747

Answers (2)

Pradeep Nooney
Pradeep Nooney

Reputation: 820

  return new Promise(function (resolve, reject) {
    axios
        .get(imgSrcURl, {
                responseType: 'arraybuffer'
            })
        .then(response => {
            var data_url = Buffer.from(response.data, 'binary').toString('base64');
            data_url = "data:application/octet-stream;base64," + data_url;
            fabric.Image.fromURL(
                data_url,
                img => {
                    resolve(img);
                });
        });
});

Upvotes: 1

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

If your response text is a binary string containing the image data, you can build a dataurl and from datayurl load a standard image.

function downloadButtonPressed() {
    var username = $("input#username").val();
    var password = $("input#password").val();
    $.ajax({
        type: "GET",
        url: "http://myserver/myapp/map",
        headers: {
            "Authorization": "Basic " + btoa(username + ":" + password),
        },
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        success: function (data, status, xhr) {
            alert("success");
        }
    }).fail(function ($xhr) {
        var myDataURL = "data:image/png;base64," + btoa($xhr.responseText);
        var img = document.createElement("IMG");
        img.onload = function(){
            var fImg = new fabric.Image(img, {options});
        }
        img.src = myDataURL
    });
}

If your response is a utf8 string, thus generating an error for illegal character, as stated by MDN, try this alternative solution to convert it in base 64:

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

function utf8_to_b64(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}

btoa(unescape(encodeURIComponent($xhr.responseText)));

Upvotes: 2

Related Questions