javascript - Webgl 跨源图像不起作用

标签 javascript html nginx cors webgl

我在跨源图像方面遇到了一些问题,希望您能提供帮助。

这是行为。 我有 2 个域,例如: - domain1.com - domain2.com

在 domain1 上我放了很多 html5 游戏。此域只是游戏的存储库。

Domain2 是真正的网站(wordpress 网站),用户可以在其中玩托管在 domain1 上的游戏。 为此,我为每个游戏都发出了 curl 请求。

在 domain1 nginx 配置文件中,我放置了这些代码行以启用跨源资源共享:


    location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|json|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|swf|mp3|xml|woff2)$ {
        add_header "Access-Control-Allow-Origin" "*";
        access_log off;
        log_not_found off;
        expires max;
    }

这解决了很多游戏的一些问题,但有些游戏仍然无法运行,我收到此 js 错误:


    Uncaught DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at http://domain1.com/html5-games/action/candy-match/images/loadingbarbackground-sheet0.png may not be loaded.
        at GLWrap_.loadTexture (http://domain1.com/html5-games/action/candy-match/c2runtime.js:2618:16)
        at pluginProto.Type.typeProto.loadTextures (http://domain1.com/html5-games/action/candy-match/c2runtime.js:18070:46)
        at pluginProto.Instance.instanceProto.onCreate (http://domain1.com/html5-games/action/candy-match/c2runtime.js:18146:13)
        at Runtime.createInstanceFromInit (http://domain1.com/html5-games/action/candy-match/c2runtime.js:4806:8)
        at Layer.createInitialInstances (http://domain1.com/html5-games/action/candy-match/c2runtime.js:7541:25)
        at Layout.startRunning (http://domain1.com/html5-games/action/candy-match/c2runtime.js:6715:10)
        at Runtime.go_loading_finished (http://domain1.com/html5-games/action/candy-match/c2runtime.js:4067:36)
        at Runtime.go (http://domain1.com/html5-games/action/candy-match/c2runtime.js:3966:9)
        at http://domain1.com/html5-games/action/candy-match/c2runtime.js:4025:60

我在网上做了一些调查,发现了类似这样的文章 https://webglfundamentals.org/webgl/lessons/webgl-cors-permission.html Drawing images to canvas with img.crossOrigin = "Anonymous" doesn't work

但它们不是很有帮助。

我不想修改原始游戏文件。我正在寻找服务器端解决方案(如果存在)。如果没有,您有解决我的问题的想法吗?

我的配置有问题吗?我错过了什么吗?

谢谢你的帮助。

瓦莱里奥

最佳答案

游戏必须请求跨源图像。仅仅返回正确的 header 是不够的。如果游戏本身不通过设置 crossOrigin 属性请求跨源图像,那么浏览器将不允许使用图像,即使它们具有正确的 header 也是如此。

举个例子

const gl = document.createElement("canvas").getContext("webgl");
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);

loadImage('https://i.imgur.com/ZKMnXce.png', false);
loadImage('https://i.imgur.com/u6VI8xz.jpg', true);

function loadImage(url, crossOrigin) {
  const img = new Image();
  img.onload = () => { upload(img); };
  if (crossOrigin) {
    img.crossOrigin = '';
  }
  img.src = url;
}

function upload(img) {
  // trap for cors error
  try {
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
    log(img.src, "uploaded image");
  } catch (e) {
    log(img.src, e);
  }
}

function log(...args) {
  const elem = document.createElement("pre");
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}
pre { margin: 0; }

在这里您甚至可以看到那些第一张图片返回的 CORS header 不允许使用,因为未设置 crossOrigin

enter image description here

第二张图片具有相同的标题,但它可以工作,因为我们设置了 crossOrigin 属性

enter image description here

请注意,您可能可以在游戏脚本之前包含这样的脚本,以破解 CORS 支持。

(function() {

function isSameOrigin(url) {
  return (new URL(url, window.location.href)).origin === window.location.origin;
}

function needsCORS(url) {
  // not sure all the URLs that should be checked for
  return !isSameOrigin(url) && !url.startsWith("blob:") && !url.startsWith("data:");
}

const srcSetFn = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src').set; 

Object.defineProperty(HTMLImageElement.prototype, 'src', {
  enumerable: true,
  set: function(url) {
     if (needsCORS(url)) {
       // Set if not already set
       if (this.crossOrigin !== undefined) {
         this.crossOrigin = '';
       }
     } else {
       this.crossOrigin = undefined;
     }
     // Set the original attribute
     srcSetFn.call(this, url);
  },
});

}());

关于javascript - Webgl 跨源图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422356/

相关文章:

javascript - 使用 margin-top 滚动视差

javascript - NodeJS 和 MySQL 中标记系统的 3 个表更新的最佳方法

html - css,居中两位数 <li>

jquery - 如何在使用 css 悬停后隐藏文本?

nginx - 将自定义 nginx.conf 与 Chef Cookbook 结合使用

django - Nginx不提供静态服务

javascript - 打印网页时在每个打印页面的底部添加文本页脚

javascript - 如何获取所有表单触发器(不仅仅是当前脚本)?

html - 将垂直类别菜单变成手机上的下拉菜单

angular - 使用 try_files 指令禁用单个文件的缓存