这个问题也是在项目开发中遇到的,在游戏中要显示用户的头像,但用户头像是来自微信的网址,而cocos creator必须发布成nitave才会支持跨域。研究了好久也查了很多资料。下面代码亲测可有效跨域。以ajax异步将微信的图片地址发送到PHP的服务端转成base64码。然后在由cocos creator 渲染。废话不多说了线上代码!如果遇到问题可留言给我!
PHP代码:
header('Access-Control-Allow-Origin:*');
$img = file_get_contents("http://192.168.0.173/123.jpg");
$url = "data:image/png;base64,".base64_encode($img);
echo json_encode(['data'=>$url]);
cocos creator js代码:
//跨域获取图片 tools.js
CacheNetImg:function(Url,callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
var response = xhr.responseText;
var response = JSON.parse(response);
var img = new Image();
img.src = response.data;
var texture = new cc.Texture2D();
texture.generateMipmaps = false;
texture.initWithElement(img);
texture.handleLoadedTexture();
var newframe = new cc.SpriteFrame(texture);
callback(newframe);
//self.NoticeBg.getComponent(cc.Sprite).spriteFrame = newframe;
}
};
xhr.open("GET", cc.vv.Socket.NetImg+Url, true);
xhr.send();
},
调用方式:
cc.vv.Tools.CacheNetImg(user.img_url,function(newframe){
self.UserHead.getComponent(cc.Sprite).spriteFrame = newframe;
self.UserHead.node.setContentSize(92,92);
});