How to wait for the multiple images to load in the canvas and convert to base64?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm trying to get a base64 version of a canvas in HTML5.



Currently, the base64 image that I get from the canvas is blank.



I have found similar questions for example this one:



HTML Canvas image to Base64 problem



However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.



I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.



This is my code:






var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>





and this is a working FIDDLE:



https://jsfiddle.net/3p3e6Ldu/1/



Can someone please advice on this issue?



Thanks in advance.



EDIT:



As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.



Like so:https://jsfiddle.net/3p3e6Ldu/4/










share|improve this question

























  • You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

    – Mr Zach
    Dec 3 '17 at 20:25











  • @MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

    – David Hope
    Dec 3 '17 at 20:29











  • The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

    – Sirko
    Dec 3 '17 at 20:59











  • @Sirko, I have tried that too. it didn't work. did you try your suggestion?

    – David Hope
    Dec 3 '17 at 21:00




















0















I'm trying to get a base64 version of a canvas in HTML5.



Currently, the base64 image that I get from the canvas is blank.



I have found similar questions for example this one:



HTML Canvas image to Base64 problem



However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.



I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.



This is my code:






var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>





and this is a working FIDDLE:



https://jsfiddle.net/3p3e6Ldu/1/



Can someone please advice on this issue?



Thanks in advance.



EDIT:



As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.



Like so:https://jsfiddle.net/3p3e6Ldu/4/










share|improve this question

























  • You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

    – Mr Zach
    Dec 3 '17 at 20:25











  • @MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

    – David Hope
    Dec 3 '17 at 20:29











  • The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

    – Sirko
    Dec 3 '17 at 20:59











  • @Sirko, I have tried that too. it didn't work. did you try your suggestion?

    – David Hope
    Dec 3 '17 at 21:00
















0












0








0








I'm trying to get a base64 version of a canvas in HTML5.



Currently, the base64 image that I get from the canvas is blank.



I have found similar questions for example this one:



HTML Canvas image to Base64 problem



However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.



I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.



This is my code:






var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>





and this is a working FIDDLE:



https://jsfiddle.net/3p3e6Ldu/1/



Can someone please advice on this issue?



Thanks in advance.



EDIT:



As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.



Like so:https://jsfiddle.net/3p3e6Ldu/4/










share|improve this question
















I'm trying to get a base64 version of a canvas in HTML5.



Currently, the base64 image that I get from the canvas is blank.



I have found similar questions for example this one:



HTML Canvas image to Base64 problem



However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.



I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.



This is my code:






var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>





and this is a working FIDDLE:



https://jsfiddle.net/3p3e6Ldu/1/



Can someone please advice on this issue?



Thanks in advance.



EDIT:



As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.



Like so:https://jsfiddle.net/3p3e6Ldu/4/






var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>





var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;




var imageObj1 = new Image();

imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};

var imageObj2 = new Image();


imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};

// get png data url
//var pngUrl = canvas.toDataURL();

var pngUrl = canvas.toDataURL('image/png');

// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');


$('#base').val(pngUrl);

        <div class="contents" style="overflow-x:hidden; overflow-y:scroll;">


<div style="width:100%; height:90%;">

<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>


</div>

</div>



<p>
This is the base64 image
</p>

<textarea id="base">


</textarea>






javascript jquery html5 canvas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 3 '17 at 20:44









Rob

11.7k83054




11.7k83054










asked Dec 3 '17 at 20:02









David HopeDavid Hope

4551724




4551724













  • You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

    – Mr Zach
    Dec 3 '17 at 20:25











  • @MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

    – David Hope
    Dec 3 '17 at 20:29











  • The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

    – Sirko
    Dec 3 '17 at 20:59











  • @Sirko, I have tried that too. it didn't work. did you try your suggestion?

    – David Hope
    Dec 3 '17 at 21:00





















  • You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

    – Mr Zach
    Dec 3 '17 at 20:25











  • @MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

    – David Hope
    Dec 3 '17 at 20:29











  • The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

    – Sirko
    Dec 3 '17 at 20:59











  • @Sirko, I have tried that too. it didn't work. did you try your suggestion?

    – David Hope
    Dec 3 '17 at 21:00



















You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

– Mr Zach
Dec 3 '17 at 20:25





You can use a counter for every time an image is loaded and when all of your images is loaded, you execute the code to get the base64 data.

– Mr Zach
Dec 3 '17 at 20:25













@MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

– David Hope
Dec 3 '17 at 20:29





@MrZach, I have tried that. But I can't make it work: jsfiddle.net/3p3e6Ldu/3

– David Hope
Dec 3 '17 at 20:29













The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

– Sirko
Dec 3 '17 at 20:59





The if( count == 2 ) section in your example has to be inside the onload callbacks. You should familiarize yourself with async coding!

– Sirko
Dec 3 '17 at 20:59













@Sirko, I have tried that too. it didn't work. did you try your suggestion?

– David Hope
Dec 3 '17 at 21:00







@Sirko, I have tried that too. it didn't work. did you try your suggestion?

– David Hope
Dec 3 '17 at 21:00














1 Answer
1






active

oldest

votes


















3














In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.



However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.



I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.



A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.



const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}

// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);

// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');

// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );





share|improve this answer


























  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

    – David Hope
    Dec 3 '17 at 21:50











  • Wonderful answer!!!

    – Rob JS
    Jan 4 at 1:43












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47622709%2fhow-to-wait-for-the-multiple-images-to-load-in-the-canvas-and-convert-to-base64%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.



However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.



I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.



A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.



const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}

// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);

// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');

// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );





share|improve this answer


























  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

    – David Hope
    Dec 3 '17 at 21:50











  • Wonderful answer!!!

    – Rob JS
    Jan 4 at 1:43
















3














In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.



However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.



I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.



A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.



const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}

// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);

// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');

// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );





share|improve this answer


























  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

    – David Hope
    Dec 3 '17 at 21:50











  • Wonderful answer!!!

    – Rob JS
    Jan 4 at 1:43














3












3








3







In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.



However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.



I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.



A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.



const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}

// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);

// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');

// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );





share|improve this answer















In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.



However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.



I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.



A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.



const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;

// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}

// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);

// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');

// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 16 '18 at 18:54









lolol

2,68122743




2,68122743










answered Dec 3 '17 at 21:35









SirkoSirko

55.1k15103145




55.1k15103145













  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

    – David Hope
    Dec 3 '17 at 21:50











  • Wonderful answer!!!

    – Rob JS
    Jan 4 at 1:43



















  • I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

    – David Hope
    Dec 3 '17 at 21:50











  • Wonderful answer!!!

    – Rob JS
    Jan 4 at 1:43

















I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

– David Hope
Dec 3 '17 at 21:50





I was just reading another question about this cross domian issue and you posted this answer. Thank you for clarifying everything.

– David Hope
Dec 3 '17 at 21:50













Wonderful answer!!!

– Rob JS
Jan 4 at 1:43





Wonderful answer!!!

– Rob JS
Jan 4 at 1:43




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47622709%2fhow-to-wait-for-the-multiple-images-to-load-in-the-canvas-and-convert-to-base64%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Danny Elfman

Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues