Reputation: 72
I'm still new in coding and HTML5. I have a HTML5 stage with multiple canvas. I need to get the base64 image from that stage and resize it, then get the base64 image of the resized canvas. This is the code I use:
stage.toDataURL({
callback: function(dataUrl) {
var tmp_img = new Image();
tmp_img.src = dataUrl;
//resize image to 45x75
var canvas = document.getElementById('hidden_canvas');
canvas.width = 45;
canvas.height = 75;
var ctx = canvas.getContext("2d");
ctx.drawImage(tmp_img, 0, 0, canvas.width, canvas.height);
dataUrl = canvas.toDataURL();
)};
The dataUrl is correct in Chrome but when I run the code in Firefox, it seems that the Firefox didn't generate the correct base64 code.
I would really appreciate any help
Upvotes: 1
Views: 1279
Reputation: 105035
You've stumbled upon a common problem.
tmp_img.src
loads the dataUrl into your new image--but that takes time. So javascript continues with your code below that even before the image is loaded. The result is that you are sometimes trying to ctx.drawImage
before tmp_img has been fully loaded and is ready to use.
The fix is to refactor your code to use tmp_img.onload
. The .onload triggers a callback function when tmp_img is finally ready to use. The refactoring might look like this:
var tmp_img = new Image();
tmp_img.onload=function(){
//resize image to 45x75
var canvas = document.getElementById('hidden_canvas');
canvas.width = 45;
canvas.height = 75;
var ctx = canvas.getContext("2d");
ctx.drawImage(tmp_img, 0, 0, canvas.width, canvas.height);
dataUrl = canvas.toDataURL();
}
tmp_img.src = dataUrl;
// more javascript
JavaScript will execute the above code in this order:
tmp_img.src
and start loading the image.It looks like you're using KineticJS--are you?
If so, then instead of stage.toDataURL
you could use stage.toImage
. That way you already have the image loaded when the stage.toImage callback is executed (you don't have to worry about waiting for the image to load). Then just .drawImage the image that KineticJS provides in the callback.
Upvotes: 2