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 Answer 1

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 }); 
Sign up to request clarification or add additional context in comments.

6 Comments

I get Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. The html file and image are on desktop.
@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.
@IonVasile This looks like a different problem. Is it working when you set the src of your image to http://placehold.it/25x30?
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.
jsfiddle.net/q9kfh2pc/1 and this is when I render on page and is working: jsfiddle.net/q9kfh2pc/2
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.