0

I have a Javascript function that create a canvas, write a image and a text on it. At the and I need the base64 dataUrl but what I get is only a blank canvas.

This is my function:

 function createBreadCrumb(label) {

    var canvas = document.createElement('canvas');
        canvas.width = 25;
        canvas.height = 30;

        var img = new Image;
        img.src = 'map-pin-breadcrumb.png';


        var ctx=canvas.getContext("2d");

        img.onload = function(){

            ctx.drawImage(img, 0, 0);
            ctx.font = "11px Arial";
            ctx.textAlign="center"; 
            ctx.fillText(label, 12, 16);


        };


       return canvas.toDataURL();

}

1 Answers1

2

You are calling toDataURL before the image is loaded. As a result, none of your canvas instructions have run yet. Because the image is loaded asynchronously, you cannot get the resulting canvas synchronously and must use a callback or a promise.

Try this.

function createBreadCrumb(label, callback) {

    var canvas = document.createElement('canvas');
        canvas.width = 25;
        canvas.height = 30;

        var img = new Image;
        var ctx = canvas.getContext("2d");

        img.onload = function(){

            ctx.drawImage(img, 0, 0);
            ctx.font = "11px Arial";
            ctx.textAlign="center"; 
            ctx.fillText(label, 12, 16);

            callback(canvas.toDataURL());
        };

        img.src = 'map-pin-breadcrumb.png';
}

createBreadCrumb("hello", function(crumb){
  // do your stuff
});
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
  • I get Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. The html file and image are on desktop. – Sebastian Corneliu Vîrlan Jun 23 '16 at 08:54
  • 1
    @IonVasile the image must not be loaded using the file:// protocol but using a server so you can load it using http(s)://. If from different domain make sure you can use crossOrigin with the image. Otherwise this error will be thrown. –  Jun 23 '16 at 08:55
  • @IonVasile This looks like a different problem. Is it working when you set the `src` of your image to [http://placehold.it/25x30](http://placehold.it/25x30)? – Quentin Roy Jun 23 '16 at 08:59
  • If I have a canvas on page the image and text is rendered on page. I have same error if I set a external image url. – Sebastian Corneliu Vîrlan Jun 23 '16 at 10:13
  • https://jsfiddle.net/q9kfh2pc/1/ and this is when I render on page and is working: https://jsfiddle.net/q9kfh2pc/2/ – Sebastian Corneliu Vîrlan Jun 23 '16 at 10:15
  • As @K3N said, this is because you do not have the rights to fetch the image of your first fiddle. – Quentin Roy Jun 24 '16 at 17:08