three.js中使用canvas生成动态纹理贴图

three.js小白的学习之路。

今天分享一个使用canvas生成纹理,然后通过CanvasTexture类创建贴图的例子。

1.canvas纹理

生成一个圆形的canvas纹理,颜色随机,半径随机,圆心随机。

先创建一个随机函数:

TypeScript 复制代码
const rand = (min: number, max: number) => {
  return (Math.random() * (max - min) + min) | 0;
};

Math.random()方法生成一个 [0, 1) 的数据,结合上述计算生成一个 [min, max)区间内的数。

然后根据这个方法随机生成颜色rgb,半径和圆心。

首先颜色,颜色可以使用十六进制数来表示,从 0x000000 到 0xffffff 的范围内均表示一个颜色,由于生成的结果是左包右不包,所以代码如下:

TypeScript 复制代码
rand(0, 0x1000000)

然后再转成十六进制:

TypeScript 复制代码
rand(0, 0x1000000).toString(16).padStart(6, "0")

半径和圆心就比较简单,半径给到[16, 64)范围,圆心不超过canvas的画布大小即可:

TypeScript 复制代码
  const x = rand(0, ctx.canvas.width);
  const y = rand(0, ctx.canvas.height);
  const radius = rand(16, 64);

整体的生成圆的代码如下:

TypeScript 复制代码
const drawRandomCircle = (ctx: CanvasRenderingContext2D) => {
  ctx.fillStyle = `#${rand(0, 0x1000000).toString(16).padStart(6, "0")}`;
  ctx.beginPath();

  const x = rand(0, ctx.canvas.width);
  const y = rand(0, ctx.canvas.height);
  const radius = rand(16, 64);
  ctx.arc(x, y, radius, 0, 2 * Math.PI);
  ctx.fill();
};

2.canvas转three.js的纹理

使用的是Three.CanvasTexture类:

TypeScript 复制代码
const ctx = document.createElement("canvas").getContext("2d")!;
ctx.canvas.width = 256;
ctx.canvas.height = 256;
ctx.fillStyle = "#FFF";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const texture = new Three.CanvasTexture(ctx.canvas);

3.创建载体盒子

这就是很基础的创建一个BoxGeometry,然后将纹理赋值给材质的属性map:

TypeScript 复制代码
  const geometry = new Three.BoxGeometry();
  const material = new Three.MeshBasicMaterial({
    map: texture,
  });
  const cube = new Three.Mesh(geometry, material);
  scene.add(cube);

4.循环生成圆,更新纹理贴图

在loop循环中,循环调用生成canvas纹理的方法,从而可以多次生成不同圆心、颜色、半径的圆,同时旋转立方体Box:

TypeScript 复制代码
function render(time: number) {
  time *= 0.001;

  cube.rotation.x = time;
  cube.rotation.y = time;

  ctx && drawRandomCircle(ctx);
  texture.needsUpdate = true;

  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

5.结果

相关推荐
Mr Xu_4 小时前
告别冗长 switch-case:Vue 项目中基于映射表的优雅路由数据匹配方案
前端·javascript·vue.js
前端摸鱼匠4 小时前
Vue 3 的toRefs保持响应性:讲解toRefs在解构响应式对象时的作用
前端·javascript·vue.js·前端框架·ecmascript
sleeppingfrog4 小时前
zebra通过zpl语言实现中文打印(二)
javascript
未来之窗软件服务6 小时前
未来之窗昭和仙君(六十五)Vue与跨地区多部门开发—东方仙盟练气
前端·javascript·vue.js·仙盟创梦ide·东方仙盟·昭和仙君
baidu_247438616 小时前
Android ViewModel定时任务
android·开发语言·javascript
VT.馒头6 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
有位神秘人6 小时前
Android中Notification的使用详解
android·java·javascript
phltxy7 小时前
Vue 核心特性实战指南:指令、样式绑定、计算属性与侦听器
前端·javascript·vue.js
Byron07078 小时前
Vue 中使用 Tiptap 富文本编辑器的完整指南
前端·javascript·vue.js
Mr Xu_9 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构