Mohammad Fakira
Mohammad Fakira

Reputation: 25

canvas.toDataURL() not working properly except mozilla firefox

I have developed a coupon generator module in the site I create a coupon in the html format and fill that html value in canvas by using JavaScript function which is

function checkcanvas(id) {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var data = "<svg xmlns='http://www.w3.org/2000/svg' width='437' height='262'>" 
        +  "<foreignObject width='100%' height='100%'>"
        + "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>"
        +  $("#coupon_td").html()
        + "</div>"
        + "</foreignObject>"
        + "</svg>";

    var DOMURL = self.URL || self.webkitURL || self;
    var img = new Image();
    var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
    var url = DOMURL.createObjectURL(svg);
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(url);
    };
    img.src = url;

    if(id == 2) {
        document.getElementById('base_64_img').value = canvas.toDataURL();
    }
}

base_64_img is just a hidden element so I can post the data into my php code and create a image using base64 code.

The biggest issue I am facing that this code perfectly worked in Mozilla Firefox almost every version but not working in Google chrome.

Upvotes: 0

Views: 3343

Answers (1)

thomasbabuj
thomasbabuj

Reputation: 3919

In your code you are generating an "SVG IMAGE" and trying to convert into toDataURL().

var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});

This is the problem, from this URL toDataURL :

If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.

In this fiddlecode if you see the printed output , "data:image/png;base64". its supposed to be "data:image/svg;base64".

Instead of creating svg image, use canvas element and javascript to draw the related banner image and if you take the output then try copy & paste in your browser. ( it may work ).

Check this js plugin called SVG.toDataURL

Hope this helps.

Upvotes: 1

Related Questions