webGL&& jsFiddle - 未下载图像

时间:2016-04-11 14:32:54

标签: javascript cors webgl jsfiddle imagedownload

我试图在jsFiddle上使用webGL,但我无法在代码中下载和使用图像。一切都运行良好的运行页面我的示例在localhost但jsFiddle不接受图像。我很想在网上分享我的代码,但我无法......

这就是我将图片下载到脚本中的方式:

var image = document.createElement("img");
image.src = "http://s29.postimg.org/ct644q1dz/sp_dom1.jpg";
image.onload = function() {
        // some magic :P
        ...
}; 

There就是我的问题的例子 你知道怎么解决它吗?

1 个答案:

答案 0 :(得分:2)

WebGL requires CORS (cross origin resource sharing) permissions for images because your image is not from the same origin. In other words the image is not from jsfiddle.net it's from s29.postimg.org

Whether or not you can solve it is up to the server of the image. In this case s29.postimg.org. It has to give permission to use the image.

You also have to request those permissions.

Add

image.crossOrigin = "";  // added
image.src = ...

If it still doesn't work then postimg.org doesn't give permission.

Let's try it here

[
  "https://s29.postimg.org/ct644q1dz/sp_dom1.jpg",
  "https://i.imgur.com/lsQoyEIm.png",
  "https://c2.staticflickr.com/2/1638/26142586042_8815f263b7.jpg",
].forEach(loadImage);
  
function loadImage(url) {
  var image = document.createElement("img");
  var hostname = (new URL(url)).hostname;
  image.crossOrigin = "";
  image.src = url;
  image.onload = function(e) {
    log("**CAN** use image " + e.target.src + 
        ". Permission given by " + hostname);
  }; 
  image.onerror = function(e) {
    log("can **NOT** use image '" + e.target.src + 
        "'. Permission not given by " + hostname);
  }
}

function log(msg) {
  var elem = document.createElement("p");
  elem.appendChild(document.createTextNode(msg));
  document.body.appendChild(elem);
}

From the above test it appears postimg.org does not give permission but both imgur.com and flickr.com do.

See https://hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/