2013-12-19 67 views
5

Here你会发现一个jsFiddle改编的问题。用户上传的纹理在three.js

我想创建一个3D Web应用程序中,用户能够选择自己的本地计算机上的图像文件:

<input id="userImage" type="file"/> 

当选择了一个文件,加载图像作为一个参数一个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; 
}); 

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

Cross-origin image load denied by Cross-Origin Resource Sharing policy. 

我知道有问题与试图访问跨域资源的WebGL,但在同一时间,我看到了下面的解决在official specification for WebGL是提供:

The following ECMAScript example demonstrates how to issue a CORS request for an image coming from another domain. The image is fetched from the server without any credentials, i.e., cookies.

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"; 

在我的代码中,您看到我已为图像对象指定了crossOrigin参数,但仍然收到错误消息。我的例子与规范有什么不同? WebGL中的本地资源甚至可以像托管在另一台服务器上的资源一样使用?除此之外,是否还有其他解决方法,我应该考虑完成此任务?

回答

5

该解决方案实际上被证明通常用于preview local images之前,比如将其上传到服务器。您尝试呈现的图像会转换为数据网址,而不适用有关跨产地政策的限制。更正后的代码位于here。下面是它的肉:

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]); 
} 
2

我也有这个问题,但我几乎确切的代码只有我用

var map = THREE.ImageUtils.loadTexture(e.target.result); 

所以我有

var image = document.createElement('img'); 
var texture = new THREE.Texture(image); 
image.onload = function() { 
    texture.needsUpdate = true; 
}; 
替换该代码

并且解决了这个问题..