Vue中如何将URL图片转为Base64?调用方法时遇类型错误
解决Vue中Facebook登录图片转Base64时的
this.getDataUri is not a function错误 先看你遇到的错误:
all.js:108 Uncaught TypeError: this.getDataUri is not a function
这个问题的核心是**this的指向出了问题**。在FB.api的回调函数里,this已经不再指向你的Vue组件实例了,而是指向了FB内部的上下文对象,所以自然找不到你定义在组件里的getDataUri方法。我给你几个简单的修复方案,同时还会修正你代码里的其他小问题:
一、修复this指向的三种方法
方法1:用箭头函数作为回调
箭头函数会自动继承外层作用域的this,也就是你的Vue组件实例:
retrivePhoto(id){ FB.api('/'+id+'/picture?redirect=false&height=120&width=120','GET',{}, (response) => { this.getDataUri(response.data.url, (base64) => { console.log(base64); // 这里拿到转换后的Base64 }); }); }
方法2:提前保存组件的this到变量
把组件实例的this存到一个变量(比如vm)里,在回调里用这个变量调用方法:
retrivePhoto(id){ const vm = this; // 保存组件实例的引用 FB.api('/'+id+'/picture?redirect=false&height=120&width=120','GET',{}, function(response) { vm.getDataUri(response.data.url, (base64) => { console.log(base64); }); }); }
方法3:用bind绑定this
给回调函数手动绑定组件实例的this:
retrivePhoto(id){ FB.api('/'+id+'/picture?redirect=false&height=120&width=120','GET',{}, function(response) { this.getDataUri(response.data.url, (base64) => { console.log(base64); }); }.bind(this)); // 绑定this到组件实例 }
二、修正getDataUri方法里的其他问题
你的getDataUri还有几个小bug,一起改了:
getDataUri(url, callback){ let image = new Image(); // 必须加跨域设置,否则Facebook图片无法在canvas中处理 image.crossOrigin = 'anonymous'; image.onload = () => { let canvas = document.createElement('canvas'); // 这里的this要改成image,之前指向错了 canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; canvas.getContext('2d').drawImage(image, 0, 0); // 注意是toDataURL(大写URL),不是toDataUrl const fullBase64 = canvas.toDataURL('image/png'); const pureBase64 = fullBase64.replace(/^data:image\/(png|jpg);base64,/, ''); // 建议只调用一次callback,或者分两次传不同参数,避免重复执行 callback(pureBase64, fullBase64); }; image.src = url; }
这里要注意两个关键点:
- 跨域设置:Facebook的图片属于跨域资源,必须设置
image.crossOrigin = 'anonymous',否则canvas调用toDataURL会抛出跨域错误。 - 方法拼写:是
toDataURL(大写的URL),不是你之前写的toDataUrl,小写的话会找不到这个方法。
内容的提问来源于stack exchange,提问作者Bruno Justino Praciano
相关产品推荐
相关产品推荐

