I have a function that works in the console when i step through it but doesn't work on the device when i run it normally.
I think the problem is the callback(t)
runs before the result of the render function has finished.
var MAX_HEIGHT = 740;
function render(src) {
var image = new Image();
image.src = src;
var out = '';
image.onload = function () {
var canvas = document.createElement("canvas");
if (image.height > MAX_HEIGHT) {
image.width *= MAX_HEIGHT / image.height;
image.height = MAX_HEIGHT;
}
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
console.log('resized: ', canvas.toDataURL("image/jpeg", 1.0));
out = canvas.toDataURL("image/jpeg", 1.0);
};
return out;
}
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
var t = render(reader.result);
callback(t);
console.log(t);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
How can I make it so the callback()
only runs once the render()
has finished