Here您将找到问题的jsFiddle改编。

我想创建一个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提供了以下解决方法:


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中的本地资源吗?除此以外,我还有其他解决方法可以考虑完成任务吗?

最佳答案

实际上,该解决方案通常在preview local images(例如,将它们上传到服务器)之前用于here。您尝试渲染的图像将转换为数据URL,其中对跨源策略的限制不适用。更正后的代码位于ojit_a。其实质是:

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

07-28 03:24
查看更多