小程序使用THREE.CanvasTexture真机贴图异常的问题处理

原因:微信客户端的 textImage2D 暂时不支持 Uint8ClampedArray,后续版本可能会修复

处理:

暂时用Uint8Array规避下问题,使用THREE.DataTexture加载Uint8Array的imageData,生成纹理。

/**
     * 小程序生成canvas的纹理贴图
     * @param {canvas} canvas 
     * @author Su Jiantao
     */
export function creatTexture(canvas) {
  const ctx = canvas.getContext('2d');
  const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height),
  bbb = [];

  // getImageData会有上下翻转的情况,需要重新排列
  for (var i = 0; i < canvas.height; i++) {
    bbb.unshift(...Array.prototype.slice.call(imgData.data, i * canvas.width * 4, (i + 1) * canvas.width * 4));
  }
  for (var i = 0; i < bbb.length; i++) {
    imgData.data[i] = bbb[i];
  }
  const pixels = new Uint8Array(imgData.data.buffer)
  const texture = new THREE.DataTexture(pixels, canvas.width, canvas.height)
  texture.needsUpdate = true;
  return texture
}

export function createCanvas(width, height) {
  if (!document) {
    return wx.createOffscreenCanvas({ type: '2d', width, height })
  } else {
    return document.createElement('canvas')
  }
}

你可能感兴趣的:(three.js,小程序,小程序)