【发布时间】:2018-07-28 06:13:54
【问题描述】:
我在将缩略图生成功能转换为承诺时遇到了一些问题。
我需要它,以便它在生成缩略图后运行 Promise.all,目前拇指未定义(这是有道理的,因为它需要首先生成)。
我不明白 img.onload 的第一部分,我的解决方法是将其设置在 $scope 上,我知道这是一种糟糕的数据传递方式。
var img = new Image;
img.onload = resizeImage;
img.src = $scope.imageData;
function resizeImage() {
var newDataUri = imageToDataUri(this, 100, 100);
$scope.imageDataThumb = newDataUri;
$scope.$apply();
}
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
var quality = 1.0;
return canvas.toDataURL('image/jpeg', quality).split(",")[1]; // quality = [0.0, 1.0]
}
var imgGuid = factory.guid();
//Save the image to storage
console.log($scope.imageDataThumb);
Promise.all([fireBaseService.postImageToStorage(imageData, "images", imgGuid), fireBaseService.postImageToStorage($scope.imageDataThumb, "images", "thumb_" + imgGuid)])
.then(function (results) {
//do stuff with results
});
【问题讨论】:
-
好像你的代码被/被剪掉了。
-
嗨@MarkSchultheiss - 这只是保存缩略图图像的服务调用的开始
-
当心,@Bergi 在his comment 中是正确的:您的问题是由您的一个简单的异步错误处理引起的。其实和this Q/A是同一个核心问题。如果接受的答案似乎对您有用,那仅仅是因为您尝试的图像加载时间不到 4 毫秒。对于更大的图像,您将面临同样的问题。你应该从这个答案中得到的唯一一行是“我建议也将移动图像加载到承诺中”。
标签: javascript canvas promise q