我正在使用' Resize-base64' (https://github.com/dizhar/resize-base64)在Angular中。当我传递base64字符串时,我控制台登录脚本以仔细检查正确接收的值。他们是。但是,当它出现在' var img = newImage()'时,它会创建图像,但似乎需要几秒钟的时间用base64字符串填充src属性。因此,当我控制log' img.width和height'时,它们全部返回为' 0'因此,抛出错误:
无法执行' drawImage' on' CanvasRenderingContext2D':图像参数是宽度或高度为0的画布元素。
有没有办法确保在脚本的其余部分运行之前填充src属性?或者,我错过的错误是否有明显的原因?
我的角色组件
setLargeImageDimensions(resetBase64Image) {
var img = resizebase64(resetBase64Image, 1000, 1000);
}
' Resize-Base64节点模块/脚本
module.exports = function(base64, maxWidth, maxHeight){
console.log('base64 = ', base64);
console.log('maxWidth = ', maxWidth);
console.log('maxHeight = ', maxHeight);
// Max size for thumbnail
if(typeof(maxWidth) === 'undefined') maxWidth = 500;
if(typeof(maxHeight) === 'undefined') maxHeight = 500;
// Create and initialize two canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
var copyContext = canvasCopy.getContext("2d");
var canvasID = canvas.setAttribute('id', 'resize-base64');
// Create original image
var img = new Image();
img.src = base64;
// Determine new ratio based on max size
var ratio = 1;
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;
// Draw original image in second canvas
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
// Copy and resize second canvas to first canvas
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
console.log(' canvas.width = ', canvas.width);
console.log(' canvas.height = ', canvas.width );
ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
return maxWidth;
}