我有一个功能在我通过它时在控制台中工作,但在我正常运行时在设备上不起作用。
我认为问题是在渲染函数结果完成之前callback(t)
运行。
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();
}
我怎样才能使callback()
仅在render()
完成后才会运行