【问题标题】:How to render 2d text or 2d image in webgl?如何在 webgl 中渲染 2d 文本或 2d 图像?
【发布时间】:2020-06-12 15:07:23
【问题描述】:

当我尝试使用 Canvas 2d 的上下文渲染图像或文本时。我收到跨域错误。即使我做了 crossorigin ='anonymous' 它的行为也很奇怪。谁能帮我吗。这是我的代码。

未捕获的 DOMException:无法在“WebGLRenderingContext”上执行“texImage2D”:图像元素包含跨域数据,可能无法加载。 在 Image.image.onload (file:///C:/Users/***/WebGl-Integration/texture.html:312:8)

参考:https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL

function loadTexture(gl, url) {
  const texture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture);

  // Because images have to be download over the internet
  // they might take a moment until they are ready.
  // Until then put a single pixel in the texture so we can
  // use it immediately. When the image has finished downloading
  // we'll update the texture with the contents of the image.
  const level = 0;
  const internalFormat = gl.RGBA;
  const width = 1;
  const height = 1;
  const border = 0;
  const srcFormat = gl.RGBA;
  const srcType = gl.UNSIGNED_BYTE;
  const pixel = new Uint8Array([0, 0, 255, 255]);  // opaque blue
  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
                width, height, border, srcFormat, srcType,
                pixel);

  const image = new Image();
  image.src="img_the_scream.jpg";
  //image.crossOrigin="Anonymous";
  image.onload = function() {
    gl.bindTexture(gl.TEXTURE_2D, texture);

     **getting issue here**

    gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
                  srcFormat, srcType, image);

    // WebGL1 has different requirements for power of 2 images
    // vs non power of 2 images so check if the image is a
    // power of 2 in both dimensions.
    if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
       // Yes, it's a power of 2. Generate mips.
       gl.generateMipmap(gl.TEXTURE_2D);
    } else {
       // No, it's not a power of 2. Turn of mips and set
       // wrapping to clamp to edge
       gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
       gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
       gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    }
  };
  image.src = url;

  return texture;
}

function isPowerOf2(value) {
  return (value & (value - 1)) == 0;
}

【问题讨论】:

    标签: webgl webgl2


    【解决方案1】:

    您需要运行一个简单的 Web 服务器。您不能直接将图像从硬盘加载到 WebGL。

    参见thisthis 以及

    【讨论】:

    • 要学习WEBGL,我们需要学习OPENGL(GLSL)吗?因为我对 WEBGL 和画布很陌生
    • 不,你可以learn WebGL directly here
    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 2019-05-07
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多