html5 webgl 图片跨域,{html5} webgl下面跨域拉取图片的问题

在WebGL应用中,由于安全限制,无法直接通过XMLHttpRequest或img.src加载微信用户的头像,因为微信服务器未设置Access-Control-Allow-Origin。然而,可以使用canvas进行绘制来规避这个问题。在canvas中,WebGL对跨域资源的处理更为严格,但可以通过设置image.crossOrigin属性为'anonymous',并在图片加载完成后进行绘制。这种方式允许从其他域加载媒体,前提是服务器已经通过CORS策略给予了许可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要拉取微信用户头像并显示在游戏中,有两种方式:1)是使用xmlhttprequest 2)使用img.src=url。但这两种方式在webgl模式下面都不行。因为需要服务端配合设置Access-Control-Allow-Origin。而微信头像的服务器并没有设置,具体报错为:

Image from origin ‘http://wx.qlogo.cn’ has been blocked from loading by Cross-Origin Resource Sharing policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:7456’ is therefore not allowed access.

然而使用canvas绘制图片是可以的,因为webgl比canvas更严格,详情:

https://www.khronos.org/registry/webgl/specs/1.0/(搜索CORS):

WebGL necessarily imposes stronger restrictions on the use of cross-domain media than other APIs such as the 2D canvas rendering context, because shaders can be used to indirectly deduce the contents of textures which have been uploaded to the GPU.

WebGL applications may utilize images and videos that come from other domains, with the cooperation of the server hosting the media, using Cross-Origin Resource Sharing [CORS]. In order to use such media, the application needs to explicitly request permission to do so, and the server needs to explicitly grant permission. Successful CORS-enabled fetches of image and video elements from other domains cause the origin of these elements to be set to that of the containing Document [HTML].

var image = new Image();

// The onload handler should be set to a function which uploads the HTMLImageElement

// using texImage2D or texSubImage2D.

image.onload = …;

image.crossOrigin = “anonymous”;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值