Mohammad Fakira
Mohammad Fakira

Reputation: 25

issue with html5 canvas value passing in Base64

Hi i am creating a coupon generater... in this i m showing the preview of coupon by html table code.. after that i m going to convert in canvas into base64_encode

    var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var data = "data:image/svg+xml," +
           "<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'>" +
                 "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>"+$("#coupon_td").html()+"</div>" +
               "</div>" +
             "</foreignObject>" +
           "</svg>";
        var img = new Image();
        img.src = data;
        img.id = "base64_img";
        img.onload = function() { ctx.drawImage(img, 0, 0); }

        $("form").append("<input type='hidden' id='base_64_img' name='base_64_img' value='"+canvas.toDataURL()+"' />");

1st time the canvas gonna blank after that 2nd time it's going to be allright.. why this happens ?? please help me :(

Upvotes: 0

Views: 237

Answers (1)

Cantidio Fontes
Cantidio Fontes

Reputation: 11

I've runned your code here and everything works fine for me. So the only thing that maybe is breaking your code is the "image.onload". Try putting it before you set the "image.src".

Like this:

var img    = new Image();
img.onload = function() { ctx.drawImage(img, 0, 0); }
img.src    = data;
img.id     = "base64_img";

This way there's no chance that your image is ready before you set its onload callback.

Upvotes: 1

Related Questions