我是靠谱客的博主 舒服小丸子,这篇文章主要介绍WebGL自学课程(7):WebGL加载跨域纹理出错Cross-origin image load denied by Cross-Origin Resource Sharing policy.,现在分享给大家,希望可以做个参考。

最近在学习WebGL,用图片对WebGL进行纹理贴图,其中图片是从其他网站跨域获取的,用Chrome 22运行网页,开始的时候出现了错误Uncaught Error: SECURITY_ERR: DOM Exception 18,找到了解决方案,参见本人另一篇博文Uncaught Error: SECURITY_ERR: DOM Exception 18。

本人最近又从其他网站跨域获取图片加载WebGL纹理时,将图片的src进行如下设置,texture.image.src="http://services9.arcgisonline.com/arcgisoutput/_ags_meba940.jpg",结果在Chrome 22下运行网页报错如下:Cross-origin image load denied by Cross-Origin Resource Sharing policy.

此错误也就说明我们不能使用跨域图片作为纹理,既然不能将跨域图片用作WebGL纹理,那么我就想到了先把图片保存到和我们运行的网页相同的目录下,然后再加载这个本地图片,这样就可以解决问题了。

具体的做法是:

假设我现在运行WebGL的网页是demo.html,放置在LearningWebGL这个文件夹下。我们现在要解决的问题是在demo.html中用WebGL使用跨域获得的图片作为纹理,假设我们已经知道了要使用的跨域图片的url。

我的做法是,在LearningWebGL文件夹下创建一个代理文件proxy.ashx,然后在demo.html中用ajax将跨域图片的url异步发送到proxy.ashx中,然后让proxy.ashx获取图片并保存到LearningWebGL文件夹下,假如将其命名为imageName,此时的远程图片已经下载到了本地,而且是和demo.html位于同目录下。最后将图片名imageName作为ajax的响应进行输出。这样我们在demo.html的ajax执行成功后通过responseText即可获得本地的图片的名称。然后将WebGL纹理图片的src设置为对应的本地图片名称imageName即可。

以下是前端的ajax代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function storeMapImage(imageUrl){ var xmlHttpRequest = getXmlHttpRequest(); if (xmlHttpRequest == null) { alert("您的浏览器不支持XMLHttpRequest"); } else { xmlHttpRequest.onreadystatechange = function () { if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { alert("完成!"); heightMap.initTextureImageUrl(xmlHttpRequest.responseText); } }; xmlHttpRequest.open("GET", "proxy.ashx?imageUrl="+imageUrl, true); xmlHttpRequest.send(); } }

以下是代码文件proxy.ashx的代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<%@ WebHandler Language="C#" Class="proxy" %> using System; using System.IO; using System.Web; using System.Drawing; public class proxy : IHttpHandler { public void ProcessRequest(HttpContext context) { string url = context.Request["imageUrl"]; System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(url)); request.Method = context.Request.HttpMethod; request.ContentType = "application/x-www-form-urlencoded"; System.Net.WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); Image img = Image.FromStream(stream); int index = url.LastIndexOf('/'); string imageName = url.Remove(0, index+1); string baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory; string physicPath = baseDirectory + imageName; img.Save(physicPath); context.Response.Write(imageName); context.Response.End(); } public bool IsReusable { get { return false; } } }



最后

以上就是舒服小丸子最近收集整理的关于WebGL自学课程(7):WebGL加载跨域纹理出错Cross-origin image load denied by Cross-Origin Resource Sharing policy.的全部内容,更多相关WebGL自学课程(7):WebGL加载跨域纹理出错Cross-origin内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部