onload
图像完全加载后,图像实例触发事件。随之而来的另一个问题是处理异步函数。为了能够使用什么getBase64Image
用途,必须使用回调函数。没有回调函数,该函数将返回undefined
let base64image = this.getBase64Image(imgUrl); console.log(base64image); // undefined
调整功能
public getBase64Image(imgUrl, callback) { var img = new Image(); // onload fires when the image is fully loadded, and has width and height img.onload = function(){ var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL("image/png"), dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); callback(dataURL); // the base64 string }; // set attributes and src img.setAttribute('crossOrigin', 'anonymous'); // img.src = imgUrl; }
用法:
this.getBase64Image(imgUrl, function(base64image){ console.log(base64image); });