用户在three.js中上传了纹理

168*_*807 5 javascript opengl-es webgl cors three.js

在这里你会找到一个jsFiddle改编的问题.

我想创建一个3d Web应用程序,用户可以在其中选择本地计算机上的图像文件:

<input id="userImage" type="file"/>
Run Code Online (Sandbox Code Playgroud)

选择文件后,图像将作为参数加载到THREE.ShaderMaterial对象中.将glsl着色器应用于图像,并将结果呈现给浏览器中的容器:

$("#userImage").change(function(){
    var texture = THREE.ImageUtils.loadTexture( $("#userImage").val() );
    texture.image.crossOrigin = "anonymous";
    shader.uniforms.input.value = texture;
    shader.uniforms.input.needsUpdate = true;
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会导致以下错误:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.
Run Code Online (Sandbox Code Playgroud)

我知道尝试访问WebGL中的跨源资源存在问题,但同时我看到WebGL官方规范中提供了以下解决方法:

以下ECMAScript示例演示了如何为来自其他域的映像发出CORS请求.无需任何凭据即cookie即可从服务器获取映像.

var gl = ...;
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";

image.src = "http://other-domain.com/image.jpg";
Run Code Online (Sandbox Code Playgroud)

在我的代码中,您看到我已经为图像对象指定了crossOrigin参数,但我仍然收到错误.我的例子与规范有何不同?甚至可以在WebGL中使用本地资源,就像在另一台服务器上托管资源一样?除此之外,还有其他工作要考虑完成任务吗?

168*_*807 6

实际上,该解决方案通常用于在上传服务器之前预览本地图像.您尝试呈现的图像将转换为数据网址,其中有关跨源策略的限制不适用.更正的代码位于此处.以下是它的内容:

userImage = $("#userImage")[0];
if (userImage.files && userImage.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        image.src = e.target.result;
    };

    reader.readAsDataURL(userImage.files[0]);
}
Run Code Online (Sandbox Code Playgroud)