Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 602
Dmitrii Pisarenko Avatar asked Nov 29 '25 14:11

Dmitrii Pisarenko


1 Answers

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)));
like image 160
AndreaBogazzi Avatar answered Dec 01 '25 04:12

AndreaBogazzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!