我正在尝试使用canvas.toDataURL()调整图像大小并获取其base64字符串表示。
我的代码如下所示(见下文)。 我的问题是,每次我首次初始化它时,它都会返回“data:,”。
然后,当我重新调整大小(通过按钮调用)时,它就能正常工作,并返回一个非空的base64字符串。到底发生了什么?
function drawAndResizeFunction(images)
var qDraw = $q.defer();
// 1
drawCanvasWrapper().then(function(canvasData){
qDraw.resolve(canvasData)
});
// 2
function drawCanvasWrapper() {
var pResults = images.map(function (imageObj) {
//return drawCanvassIter(imageObj.tempURL); // tempUrl
return resizeIter(imageObj.tempURL).then(function(result){
console.log("resized", result) // *** RETURNS data:, in first attempt
return result;
})
});
return $q.all(pResults);
};
// 3inval
// returns canvasdata
function resizeIter(nativeURL) {
console.log("resizeIter")
var qResize = $q.defer();
var canvas = document.getElementById("resizecanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = nativeURL;
var newScales = resizeDimensions(img.width, img.height)
var iw =canvas.width =img.width =newScales.iw;
var ih =canvas.height =img.height =newScales.ih;
img.onload = function () {
// --> 4
ctx.drawImage(img, 0, 0, iw, ih);
$timeout(function(){
qResize.resolve(canvas.toDataURL("image/jpeg"));
}, 200)
};
return qResize.promise;
//
//
function resizeDimensions(iw, ih) {
var scaleFactor = 1;
var targetSize = 800;
if (iw > targetSize || ih > targetSize) {
if(iw > ih) {
scaleFactor = targetSize/iw;
} else {
scaleFactor = targetSize/ih;
}
}
var iwAdj = Math.floor(iw*scaleFactor);
var ihAdj = Math.floor(ih*scaleFactor);
return {
ih: ihAdj, iw: iwAdj
}
};
};
return qDraw.promise;
}; // done