Code Monkey home page Code Monkey logo

three-platformize's Introduction

three-platformize

一个让 THREE 平台化的项目

后续维护将会在platformize继续

  1. 目前已适配微信,淘宝,字节小程序
  2. 支持 tree shaking(需用 webpack,rollup 等构建工具)
  3. VSCode types 正常,能正常访问各个类的定义
  4. 适配 examples/jsm/**/*.js,types 正常
  5. 可升级、降级版本或使用自定义 THREE
  6. 微信小程序 IOS 内存优化,更少切页面导致的崩溃
  7. 支持自定义新平台适配,参考 WechatPlatform 编写适配器即可
  8. three-platformize-plugin-wechat 支持微信插件跨插件复用

Special Sponsors

云图三维-在线三维CAD设计软件
云图三维-在线三维CAD设计软件
奥本未来-AR/VR领域先行者
奥本未来-AR/VR领域先行者

适配情况

微信 淘宝 字节
小程序真机 ✔️ ✔️ ✔️
小程序模拟器 ✔️ ✔️
小游戏真机 ✔️
小游戏模拟器 ✔️

奥本未来招聘前端、WebGL、图形学算法,欢迎投简历

DEMO

注:运行 DEMO 时记得开启调试模式,取消域名验证,使用最新版本微信开发工具打开

具体 Loader 使用方法的 Demo 在这个仓库下three-platformize-demo

微信小程序 DEMO
微信小程序基础版 DEMO
微信小游戏 DEMO
淘宝小程序 DEMO 字节小程序 DEMO

已测试模块

Features

  1. VSMShadow (r131以及之前的版本可以, 见Loop index cannot be compared with non-constant expression)

Loader

  1. GLTFLoader (支持带纹理的 GLB) && (EXT_meshopt_compression 安卓可用 WASM,ios 可用 ASM 版,见 tools) && (KHR_mesh_quantization,小程序可用) 【网格压缩测评】MeshQuan、MeshOpt、Draco (微信 8.0 后 WebAssembly API 已无法使用需要使用 WXWebAssembly, 且只支持包内 wasm, 已新增 meshopt_decoder.wasm.module, 使用见)
  2. TextureLoader
  3. RGBELoader & PMREMGenerator (小程序部分机型可能偶现生成 envMap 错误,可用HDRPrefilter避免 )
  4. SVGLoader
  5. OBJLoader
  6. EXRLoader (需支持 OES_texture_float_linear 扩展,部分移动端 GPU 不支持)
  7. MTLLoader (小程序使用 JPG 纹理即可)
  8. DDSLoader (需支持 WEBGL_compressed_texture_s3tc 扩展,移动端 GPU 不支持)
  9. LWOLoader (需支持 EXT_blend_minmax 扩展,小程序一半效果绘制出错)
  10. FBXLoader
  11. BVHLoader
  12. ColladaLoader (DOMParser querySelector 未适配)
  13. TTFLoader
  14. STLLoader
  15. PDBLoader
  16. TGALoader (改用 DataTextureLoader PR 已合并,r127 可用)
  17. VTKLoader

Controls

  1. OrbitControls & MapControls
  2. DeviceOrientationControls (微信、淘宝小程序下 onDeviceMotionChange,安卓下返回数据质量极其低下,基本不可用,社区 bug 反馈 3 年多了,官方无修复意愿)

不支持模块

  1. ImageBitmapLoader(微信小程序未开放 ImageBitmap)

Tools

  1. dispose-three(销毁节点
  2. flip(截屏需要 flipY
  3. screenshot
  4. worker-pool.module(暂未适配微信小程序
  5. zstddec.worker.module(暂未适配微信小程序
  6. zstddec.module(暂未适配微信小程序
  7. toEnvMap(用于 hdr prefilter
  8. meshopt_decoder.asm.module(微信小程序可用
  9. meshopt_decoder.wasm.module(微信小程序可用

Extensions

  1. GLTFGPUCompressedTexture(BasisTextureLoader 的代替方案) 生成工具通过gltf-gpu-compressed-texture获取(暂未适配微信小程序

使用

import * as THREE from 'three-platformize';
import WechatPlatform from 'three-platformize/src/WechatPlatform';

const platform = new WechatPlatform(canvas); // webgl canvas

platform.enableDeviceOrientation('game'); // 开启DeviceOrientation
THREE.PLATFORM.set(platform);

// 使用完毕后释放资源
THREE.PLATFORM.dispose();

// 正常使用three即可
// DEMO 代码示例见 https://github.com/deepkolos/three-platformize-demo
// 基础的使用DEMO见 https://github.com/deepkolos/three-platformize-demo-wechat-simple
// 生产环境时rollup.config.js里请开启teser压缩, 即plugins末尾增加 terser({ output: { comments: false } })

经验

  1. 微信小程序不支持 2048 以上的纹理图片
  2. 淘宝小程序显示 RGB 格式纹理 (JPG) 有问题,通过 TextureLoader 加载纹理后,把 texture.format 设置为 RGBAFromat 即可(淘宝版本 9.20.0),原因可能是服务端对图片大图片优化,把图片压缩导致格式改变 RGB 变 RGBA
  3. r126 不能设置全 pixelRatio,可以设置为一半,或者 2,不能是 3
  4. 虽然支持加载 GLB,但图片是使用 js 版的 ArrayBuffer 转 base64,耗时且占用内存,虽可用 wasm 的 encoder 缓解 (https://github.com/marcosc90/encoding-wasm),但wasm对字符串处理性能不如js,用AssemblyScript编译的wasm测试
  5. IOS 前后进入退出页面崩可以降低 pixelRatio 缓解
  6. IOS 微信 readPixels 不支持抗锯齿,如果直接 canvas 的 buffer 需要关闭抗锯齿(antialias: false), 另一种方式是 WebglRenderTarget,同时也可以开启抗锯齿,但是纹理大小受限(小米 8 下纹理宽/高不能超过 4096,需要注意先 setSize,再 setPixelRatio)(截图 Demo 见微信小程序 DEMO
  7. 淘宝小程序有严格的域名验证,可使用云存储放模型,但是如果模型和纹理分开则需要手动关联,推荐 GLB
  8. URL 的 polyfill 可以使用 fileSystemManager 来获取临时文件的方式避免 arraybuffer 转 base64, 但是需要手动管理临时文件
  9. QQ群有同学反馈在ios淘宝小程序上模型文件路径不支持中文

实现

构建时替换平台相关的 api 调用,转发到 PLATFORM 的引用,通过 PLATFORM.set 更新

维护

如何更新/降级 Three 的版本?

# 拉取源码
> git clone https://github.com/deepkolos/three-platformize

# 安装依赖
> npm i

# 更新到最新的three版本
> npm i -S three@latest
# 或者指定three版本
> npm i -S [email protected]
# 需要把目标three的构建`utils/build/rollup.config.js`同步到本项目的构建`config/rollup.config.three-origin.js`

# 建立软链接
> npm run link

# 构建
> npm run build

# 使用
> npm link

# 到使用的项目目录,并链接
> cd your-project
> npm link three-platformize

# 或者自行发NPM包

如何平台化自定义的 Three?

# 把自定义Three link 到./three
> npx symlink-dir yourthree ./three

# 不使用软链接直接复制或者git submodule也可以
> cp yourthree ./three

# 复制对应版本three构建配置替换到rollup.config.three-origin.js
> cp yourthree/utils/build/rollup.config.js ./config/rollup.config.three-origin.js

# 构建
> npm run build

如何编写自定义平台?

可参考src/WechatPlatform或者src/TaobaoPlatform

class CustomPlatform {
  getGlobals() {
    // 自定义的polyfill
    return {
      atob,
      Blob,
      window,
      document,
      XMLHttpRequest,
      OffscreenCanvas,
      HTMLCanvasElement,
      createImageBitmap,
    };
  }

  setWebGLExtensions() {
    return {
      // 可覆盖gl返回值,比如淘宝小程序IOS返回值不为null,但是扩展不可用的bug
      EXT_blend_minmax: null,
    };
  }

  dispose() {
    // 释放资源
  }
}

TODO

  1. 更彻底 dispose,减少内存泄漏,Web 测试用例已增加,微信小程序已增加,IOS 仍有内存问题,多次切页面仍会崩溃,3mb 模型 iphone7 打开 30 次
  2. 适配头条小程序 done
  3. 生成微信插件,通过插件实现 three 的代码跨小程序、跨小程序插件复用 done three-platformize-plugin-wechat
  4. 适配微信小游戏 done
  5. 适配 ReactNative

讨论

可通过群里 DeepKolos 联系我

赞助

如果项目对您有帮助或者有适配需求,欢迎打赏

赞赏码

感谢各位支持~~

时间 大佬
2021/11/10 神神
2021/09/27 阿不
2021/08/10 奥本未来
2021/07/28 Noth1ng
2021/07/09 匿名
2021/07/07 云图 CAD-刘鑫
2021/06/23 Fong
2021/06/23 刘子弃
2021/06/23 Joson
2021/06/03 仿生伏尔泰
2021/04/28 Noth1ng

three-platformize's People

Contributors

deepkolos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

three-platformize's Issues

在部分老机型上envMap无作用

如题,使用hdr贴图,并赋予到材质上时,在较新机型上(小米10、iPhone11)等正常显示贴图;但在较旧机型上(测试了iPhone6s、荣耀20)上材质呈现全黑的状态。代码如下:

rgbe载入材质

var texture
new RGBELoader().load('somewebsite/royal_esplanade_1k.hdr', function (t) {
          texture = t
          texture.mapping = THREE.EquirectangularReflectionMapping;
});

进行材质赋值

gem.envMap = texture

淘宝小程序 真机预览失败

使用 uniapp的 hbuilder创建 uniapp项目 运行到支付宝小程序 项目类型选择 淘宝小程序
在开发工具中查看一切正常 app.json 中 enableSkia 设置为true后 预览到手机时会遇到问题
THREE.$requestAnimationFrame会卡死闪退
使用canvas.requestAnimationFrame 代替 THREE.$requestAnimationFrame 后
renderer.render 时 貌似渲染位置不正确
textureLoader.load 加载图片资源 onload和onerror 都不会走

hbuilderX版本 3.1.2
小程序开发者工具版本 1.17.9
测试手机 小米MIX2S
手机淘宝版本 9.21.1

使用 npm 安装的 three-platformize 然后手动替换为github上的 three-platformize

glTFLoader error working with draco

gltfLoader 导入 draco压缩过glTF文件时, 出现错误:

VM1970 WAService.js:2 ReferenceError: Worker is not defined
at DRACOLoader.js? [sm]:323
errorReport @ VM1970 WAService.js:2
thirdErrorReport @ VM1970 WAService.js:2
(anonymous) @ VM1970 WAService.js:2
I @ VM1970 WAService.js:2
o @ VM1970 WAService.js:2
(anonymous) @ VM1970 WAService.js:2
value @ VM1970 WAService.js:2
o @ VM1970 WAService.js:2
(anonymous) @ VM1970 WAService.js:2

Working screenshot on iphone?

Hi!

I found your code snippet here https://juejin.cn/post/6920981822864097288
It works great in the WeChat Dev Tools and on Android phones, but have you been able to get it to work on an iPhone?
It does not work on the iPhone 8 and 10 that I tested it on.

It appears the readPixels return all 0 values.

Thank you for your great work on three-platformize.

微信小程序ar环境下,OrbitControls无法使用并且会导致帧数下降

import { OrbitControls } from "three-platformize/examples/jsm/controls/OrbitControls";
this.camera =new THREE.PerspectiveCamera(20, this.canvas.width / this.canvas.height, 1, 10000);
const renderer = (this.renderer = new THREE.WebGL1Renderer({
antialias: true,
alpha: true,
canvas: this.canvas,
}));
this.orbitControl = new OrbitControls(this.camera, renderer.domElement);
this.orbitControl.enableDamping = true;
this.orbitControl.dampingFactor = 0.05;

const onFrame = (timestamp) => {
// let start = Date.now()
const frame = session.getVKFrame(canvas.width, canvas.height);
if (frame) {
this.render(frame);
}
this.orbitControl?.update()
session.requestAnimationFrame(onFrame);
};
session.requestAnimationFrame(onFrame);

canvas绑定事件
onTX(e) {
this.platform.dispatchTouchEvent(e);
},

基于微信小程序开发的问题

你好,作者。我在一个推送上看到了这篇文章,觉得特别好,但是对于微信小程序端的使用我还是不太了解。新增调用后,一直有报错,能否出一期微信小程序开发的过程,直接导入开发工具进行学习,不胜感激。

微信小程序,多个canvas如何设置?

platform = new WechatPlatform(canvas);
THREE.PLATFORM.set(platform);

THREE.PLATFORM只能绑定一个?这样我多个canvas就没法同时绘图了。

在不同的页面中绘图,每个页面中都会调用THREE.PLATFORM.set(platform),会出现以下问题:

image

微信小程序无法正确加载gltf模型

image
同样的代码,加载demo自带的RobotExpressive.glb可以正常加载,但是加载我的model.glb时候却无法正常加载,不知道是否是模型大小问题,我的mode.glb文件大概1M大小,模型可以在·Online 3DViewer中正常打开,但在小程序中无法加载也没有别的错误提示。希望能得到帮助

canvas渲染成功后,卸载,会出现残留,没办法释放干净

首次渲染结果:
image

react组件卸载,删除canvas后,再次添加canvas组件后结果;
image

我把微信调试工具里元素都设置 display=none了,渲染的mesh还在界面上,请问是内部哪个元素呈现画面的,怎么清理释放掉;我把我的canvas也隐藏了,也没用
image

image
image

微信小程序引入js文件引入插件报错

import * as THREE from 'three-platformize';
import WechatPlatform from 'three-platformize/src/WechatPlatform';

three-platformize可以正常引入
提示Error: module "pages/index/three-platformize/src/WechatPlatform.js" is not defined

URL.createObjectURL 微信平台的兼容性

看过源码 发现3DMloader 最终会使用 URL.createObjectURL(Blob) 来生成 rhino3dm.js 的本地路径, 看URL.js 里的 todo说 用wx.fileSystemManager 来做临时路径,不知道搞好了吗?

另外我的项目是用 UniAPP 做的, OrbitControls 却不生效, 不管官方的demo, 还是我自己的模型,都不能使用controls 调整相机的位置

以上都是 wechatPlatform 出现的问题, H5正常

`textureLoader.loadAsync` iOS真机无法加载材质

在开发者工具一切正常,但是真机无法加载,已配置合法域名。

 try {
      texture1 = await textureLoader.loadAsync("https://xxxx/result-0.jpg")
    } catch (err) {
      wx.showToast({
        title: "加载失败",
        icon: "error",
        duration: 2000
      })
      wx.getRealtimeLogManager().error(err)
    }

catch到的error没看懂。。

[00:07:35]  {"timestamp":8743946.552416667,"type":"error","target":{"bindingScreen":0,"scale":1,"naturalWidth":5760,"complete":false,"naturalHeight":3240,"height":3240,"premultiplyAlpha":true,"width":5760,"instance":10761289472,"tagName":"IMG","nodeName":"IMG","uid":10761289472,"src":"https://xxxx/result-0.jpg","crossOrigin":"anonymous"},"currentTarget":{"bindingScreen":0,"scale":1,"naturalWidth":5760,"complete":false,"naturalHeight":3240,"height":3240,"premultiplyAlpha":true,"width":5760,"instance":10761289472,"tagName":"IMG","nodeName":"IMG","uid":10761289472,"src":"https://xxxx/result-0.jpg","crossOrigin":"anonymous"}}

当用canvas渲染文字时出错

报了以下错误:
THREE.WebGLState: TypeError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Overload resolution failed.
at Object.texImage2D (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:772)
at uploadTexture (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:811)
at setTexture2D (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:790)
at WebGLTextures.safeSetTexture2D (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:827)
at SingleUniform.setValueT1 [as setValue] (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:593)
at Function.WebGLUniforms.upload (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:678)
at setProgram (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:989)
at WebGL1Renderer.WebGLRenderer.renderBufferDirect (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:926)
at renderObject (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:949)
at renderObjects (three.js?t=wechat&s=1618569287467&v=d58a6b9e40015313318b57abd046fb5f:949)

部分代码:
`onLaunch() {
this.canvas = (await getNode('#canvas'))[0].node;
this.canvasText = (await getNode('#canvas-text'))[0].node;
this.platform = new WechatPlatform(this.canvas); // webgl canvas

this.platform.enableDeviceOrientation('game'); // 开启DeviceOrientation
THREE.PLATFORM.set(this.platform);

this.init();
this.animate();
}
changeCanvas() {
const ctx = this.canvasText.getContext('2d');
ctx.font = '16pt Arial';
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, this.canvasText.width, this.canvasText.height);
ctx.fillStyle = 'white';
ctx.fillRect(10, 10, this.canvasText.width - 20, this.canvasText.height - 20);
ctx.fillStyle = 'black';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("踏得网", this.canvasText.width / 2, this.canvasText.height / 2);
}

init() {
this.renderer = new THREE.WebGL1Renderer({
antialias: true, // 抗锯齿
});
this.renderer.setSize(this.canvas.width, this.canvas.height);

this.scene = new THREE.Scene();

this.camera = new THREE.PerspectiveCamera(70, this.canvas.width / this.canvas.height, 1, 1000);
this.camera.position.z = 500;
this.scene.add(this.camera);

this.texture = new THREE.Texture(this.canvasText);
this.material = new THREE.MeshBasicMaterial({
  map: this.texture
});
const geometry = new THREE.BoxGeometry(200, 200, 200);
this.mesh = new THREE.Mesh(geometry, this.material);
this.scene.add(this.mesh);

}

animate() {
THREE.$requestAnimationFrame(() => this.animate());
this.changeCanvas();
this.texture.needsUpdate = true;
this.mesh.rotation.y += 0.01;
this.renderer.render(this.scene, this.camera);
}`

wxml:
<Canvas type='2d' id='canvas-text' style={{ width: 64px, height: 64px}} /> <Canvas type='webgl' id='canvas' style={{ width: '750rpx', height: '750rpx'}} onTouchStart={e => this.handleToucheEvent(e)} onTouchMove={e => this.handleToucheEvent(e)} onTouchEnd={e => this.handleToucheEvent(e)} />

ps: 以上例子可以在html版本运行,附上html版本代码:

`

<title>three.js webgl - materials - canvas texture</title> <style> #drawing-canvas { position: absolute; background-color: #000000; top: 0px; right: 0px; z-index: 3000; cursor: crosshair; touch-action: none; } </style>
	<div id="info">
		<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl - canvas as a texture
		<div>click and draw in the white box</div>
	</div>
	<canvas id="canvas"></canvas>

	<script type="module">

		import * as THREE from '../build/three.module.js';

		var width = window.innerWidth,
			height = window.innerHeight / 2;
		var size = 128;
		var canvas = document.getElementById('canvas'),
			ctx = canvas.getContext('2d');

		var camera, scene, renderer, geometry, texture, mesh;

		function changeCanvas() {
			ctx.font = '16pt Arial';
			ctx.fillStyle = 'orange';
			ctx.fillRect(0, 0, canvas.width, canvas.height);
			ctx.fillStyle = 'white';
			ctx.fillRect(10, 10, canvas.width - 20, canvas.height - 20);
			ctx.fillStyle = 'black';
			ctx.textAlign = "center";
			ctx.textBaseline = "middle";
			ctx.fillText("踏得网", canvas.width / 2, canvas.height / 2);
		}

		function init() {
			renderer = new THREE.WebGLRenderer();
			renderer.setSize(width, height);
			document.body.appendChild(renderer.domElement);

			scene = new THREE.Scene();

			camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
			camera.position.z = 500;
			scene.add(camera);

			texture = new THREE.Texture(canvas);
			var material = new THREE.MeshBasicMaterial({
				map: texture
			});
			geometry = new THREE.BoxGeometry(200, 200, 200);
			mesh = new THREE.Mesh(geometry, material);
			scene.add(mesh);

			canvas.width = canvas.height = size;
		}

		function animate() {
			requestAnimationFrame(animate);

			changeCanvas();
			texture.needsUpdate = true;
			mesh.rotation.y += 0.01;
			renderer.render(scene, camera);
		}

		init();
		animate();

	</script>

</body>
`

感谢作者!

当用canvas渲染文字时出错

想在threejs 里用canvas渲染一个2d的文字,但总是报以下错误

THREE.WebGLState: TypeError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Overload resolution failed.

附上部分代码:
wxml:

<canvas type='2d' id='canvas-text' />
<canvas type='webgl' id='canvas' />

js:

onLaunch() {
	this.canvas = (await getNode('#canvas'))[0].node;
	this.canvasText = (await getNode('#canvas-text'))[0].node;
	this.platform = new WechatPlatform(this.canvas); // webgl canvas

	this.platform.enableDeviceOrientation('game'); // 开启DeviceOrientation
	THREE.PLATFORM.set(this.platform);

	this.init();
	this.animate();
}
changeCanvas() {
	const ctx = this.canvasText.getContext('2d');
	ctx.font = '16pt Arial';
	ctx.fillStyle = 'orange';
	ctx.fillRect(0, 0, this.canvasText.width, this.canvasText.height);
	ctx.fillStyle = 'white';
	ctx.fillRect(10, 10, this.canvasText.width - 20, this.canvasText.height - 20);
	ctx.fillStyle = 'black';
	ctx.textAlign = "center";
	ctx.textBaseline = "middle";
	ctx.fillText("踏得网", this.canvasText.width / 2, this.canvasText.height / 2);
}
init() {
  	this.renderer = new THREE.WebGL1Renderer({
  	  	antialias: true,   // 抗锯齿
  	});
  	this.renderer.setSize(this.canvas.width, this.canvas.height);
  	this.scene = new THREE.Scene();
  	this.camera = new THREE.PerspectiveCamera(70, this.canvas.width / this.canvas.height, 1, 1000);
  	this.camera.position.z = 500;
  	this.scene.add(this.camera);
  	this.texture = new THREE.Texture(this.canvasText);
  	this.material = new THREE.MeshBasicMaterial({
  	  	map: this.texture
  	});
  	const geometry = new THREE.BoxGeometry(200, 200, 200);
  	this.mesh = new THREE.Mesh(geometry, this.material);
  	this.scene.add(this.mesh);
}

animate() {
  	THREE.$requestAnimationFrame(() => this.animate());

	  	this.changeCanvas();
  	this.texture.needsUpdate = true;
  	this.mesh.rotation.y += 0.01;
  	this.renderer.render(this.scene, this.camera);
}

ps:以上例子能够在html版本运行(引入的是最新的three.js)
附上完整html代码:

		<!DOCTYPE html>
		<html lang="en">
			<head>
	<title>three.js webgl - materials - canvas texture</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<link type="text/css" rel="stylesheet" href="main.css">
	<style>
		#drawing-canvas {
			position: absolute;
			background-color: #000000;
			top: 0px;
			right: 0px;
			z-index: 3000;
			cursor: crosshair;
			touch-action: none;
		}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>

	<script type="module">

		import * as THREE from '../build/three.module.js';

		var width = window.innerWidth,
			height = window.innerHeight / 2;
		var size = 128;
		var canvas = document.getElementById('canvas'),
			ctx = canvas.getContext('2d');

		var camera, scene, renderer, geometry, texture, mesh;

		function changeCanvas() {
			ctx.font = '16pt Arial';
			ctx.fillStyle = 'orange';
			ctx.fillRect(0, 0, canvas.width, canvas.height);
			ctx.fillStyle = 'white';
			ctx.fillRect(10, 10, canvas.width - 20, canvas.height - 20);
			ctx.fillStyle = 'black';
			ctx.textAlign = "center";
			ctx.textBaseline = "middle";
			ctx.fillText("踏得网", canvas.width / 2, canvas.height / 2);
		}

		function init() {
			renderer = new THREE.WebGLRenderer();
			renderer.setSize(width, height);
			document.body.appendChild(renderer.domElement);

			scene = new THREE.Scene();

			camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
			camera.position.z = 500;
			scene.add(camera);

			texture = new THREE.Texture(canvas);
			var material = new THREE.MeshBasicMaterial({
				map: texture
			});
			geometry = new THREE.BoxGeometry(200, 200, 200);
			mesh = new THREE.Mesh(geometry, material);
			scene.add(mesh);

			canvas.width = canvas.height = size;
		}

		function animate() {
			requestAnimationFrame(animate);

			changeCanvas();
			texture.needsUpdate = true;
			mesh.rotation.y += 0.01;
			renderer.render(scene, camera);
		}

		init();
		animate();

	</script>

			</body>
		</html>

感谢作者!

小程序ar环境下加载纹理会在渲染一瞬间后消失

let geometry = new THREE.PlaneGeometry(2, 2);
let loader = new THREE.TextureLoader();
const texture = await loader.loadAsync(data);
const material = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
map: texture,
});

        texture.minFilter = THREE.LinearFilter;
        texture.flipY = false;
        texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
        let model = (this.model = new THREE.Mesh(geometry, material));
     
       model.rotation.set(-Math.PI / 2, 0, 0);

this.scene.add(model)

THREE.FileLoader 错误

微信小程序模拟器中跑 three-platformize-demo-wechat,点击 GLTFLoader 后程序报错,debug了一下代码,错误发生在 XMLHttpRequest.js 中,如下截图
image
data 是 ArrayBuffer 类,但是 data instanceof ArrayBuffer 却返回false。

微信官方的 threejs 兼容库大概也有同样的问题,调用 THREE.FileLoader().load(...) 回调中的数据也是错的。

微信小程序setMeshoptDecoder must be called before loading compressed files。。

微信小程序setMeshoptDecoder must be called before loading compressed files。。

import { MeshoptDecoder } from 'three-platformize/examples/jsm/libs/meshopt_decoder.module.js';
import { GLTF, GLTFLoader } from 'three-platformize/examples/jsm/loaders/GLTFLoader'
const gltfLoader = new GLTFLoader()
gltfLoader.setMeshoptDecoder(MeshoptDecoder);
这样使用应该是对的把。。

关于淘宝小程序渲染threejs

作者你好,作为一个开发者 目前正在着手准备在淘宝小程序中使用threejs,目前需要渲染的模型格式主要为 gltf格式以及dae格式。。。所以 现在 这个框架可以在生产中使用了吗~?目前还是担心出现很多未知问题

该如何正确使用这个库?

请教一下,如何使用这个库才是正确的方式?

我现在的做法是,按照文档中写的,去link这个库,然后在小程序开发工具中点“构建npm”,然后下面这句
import WechatPlatform from 'three-platformize/src/WechatPlatform';
会提示找不到,然后我会在 three-platformize 目录下 build 好 WechatPlatform.js,直接copy到我的工程目录下引用,就可以了。

上面的方法我使用 Three.js 108 版本是可以的,这个版本是微信官方插件使用的版本。
但是当我使用 126 版本的时候,新建renderer会报错
this.renderer = new THREE.WebGL1Renderer({canvas, antialias: true});
报错:
TypeError: Cannot read property 'mark' of undefined

代码出错的地方是在 WebXRManager 的构造方法中
this.setSession = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {

请教一下

  1. 使用 three-platformize 的方式是否正确
  2. 上面 renderer 的报错可能是什么原因

谢谢!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.