【问题标题】:Blank texture is rendered when HTML Canvas is used in conjucture with drawImageHTML Canvas 与 drawImage 结合使用时渲染空白纹理
【发布时间】:2020-01-04 10:04:34
【问题描述】:

我正在尝试从 url 加载图像并将其绘制到用作纹理输入的画布上。我已经在 https://jsfiddle.net/9Louwn87/25/ 上实现了这一点。我已经使用以下 sn-p 来加载图像并创建纹理

var img = new Image();
    img.onload = function() {
      canvas.width = size;
      canvas.height = size;
      ctx.drawImage(this, 0, 0, size, size);
      if(texture)
      {
        texture.needsUpdate = true;          
      }
    };
    img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
    texture = new THREE.Texture(canvas);

请任何人指出错误。

【问题讨论】:

    标签: three.js textures


    【解决方案1】:

    问题可能是因为您自己加载图像并且您从另一个域加载它,您需要请求使用图像的权限。

        var img = new Image();
        img.onload = function() {
          canvas.width = size;
          canvas.height = size;
          ctx.drawImage(this, 0, 0, size, size);
          if(texture)
          {
            texture.needsUpdate = true;          
          }
        };
        img.crossOrigin = 'anonymous'; // ----------- Add this line
        img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
        texture = new THREE.Texture(canvas);
    

    请注意,添加该行不会自动让您使用来自其他网站的图像。相反,它要求该网站允许使用该图像。一些网站(imgur、flickr、github、threejsfundamentals.org)授予该权限。大多数网站不给予许可。如果图像在同一个域上,那么您通常不希望设置crossOrigin 否则除非您的服务器配置为授予权限,否则您将无法使用本地图像,如果您不询问本地图像,则通常情况下工作就好。

    另外,如果您打开 JavaScript 控制台,您会看到此错误

    three.min.js:572 Uncaught DOMException: Failed to execute 'texImage2D'
     on 'WebGLRenderingContext': Tainted canvases may not be loaded.
    

    还有一点,您可以使用three.js 的ImageLoader 来处理此权限问题,如果图像在另一个域上,则自动设置crossDomain,如果是本地图像,则不设置它。

    const loader = new THREE.ImageLoader();
    loader.load("https://threejsfundamentals.org/threejs/resources/images/wall.jpg", function() {
          canvas.width = size;
          canvas.height = size;
          ctx.drawImage(this, 0, 0, size, size);
          if(texture)
          {
            texture.needsUpdate = true;          
          }
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 2022-08-22
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多