当前位置: 首页 > news >正文

three.js 在 webGL 添加纹理

在我们生成了3D设计之后,我们可以添加纹理使其更加吸引人。在 webGL 和 p5.js中,可以使用 gl.texImage2D() 和 texture()  API来为形状应用纹理。

使用 webGL

在 webGL 中,gl.texImage2D() 函数用于从图像文件生成2D纹理。该函数接受许多参数,包括目标,细节级别,内部格式,图像的宽度和高度,以及图像数据的格式和类型。

为了方便,我将使用 vite 搭建一个原生 js 项目。

1.创建项目

npm create vite@latest p5-demo
选:Vanilla
选:JavaScript

2.初始化项目
 cd p5-demo
 cnpm install

3.安装 p5.js
 cnpm install p5 --save

cd p5-demo
curl -O https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js

编写 three_texture.html  如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="three.min.js"></script>
</head>
<body><script>// curl -O https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js// Set up the scenevar scene = new THREE.Scene();var camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight,0.1, 1000);var renderer = new THREE.WebGLRenderer();renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);// Create a cubevar geometry = new THREE.BoxGeometry(3, 3, 3);//// 随意选一个.jpg 文件作为纹理图像var texture = new THREE.TextureLoader().load("./海边.jpg");var material = new THREE.MeshBasicMaterial({ map: texture });var cube = new THREE.Mesh(geometry, material);scene.add(cube);// Position the cameracamera.position.z = 5; // Render the scenefunction render() {requestAnimationFrame(render);cube.rotation.x += 0.01;cube.rotation.y += 0.01;renderer.render(scene, camera);}render();</script>
</body>
</html>

5.运行 npm run dev 
访问 http://localhost:5173/three_texture.html


 在 p5.js 中使用 texture() 函数可以将纹理应用到一个对象上。texture() 函数接受一个参数:纹理图像文件。

编写 p5_texture.html  如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>p5.js Texture Example</title><script src="p5.min.js"></script>
</head>
<body><script>let img;function preload() { img = loadImage("./海边.jpg");}function setup() {createCanvas(650, 400, WEBGL);noStroke();}function draw() {background(200);texture(img);rotateX(frameCount * 0.01);rotateY(frameCount * 0.01);box(100);}</script>
</body>
</html>

 访问 http://localhost:5173/p5_texture.html

 可见同样的程序 p5.js 的代码量比 three.js 和 python 都要少。


http://www.mrgr.cn/news/93632.html

相关文章:

  • Linux教学总目录
  • #UVM# 关于 config_db 机制中省略 get 语句的条件
  • 扎实基础:测试工作的基石
  • C++学习之QT基础
  • 【GPT入门】第8课 大语言模型的自洽性
  • 力扣203题:移除链表元素及代码实现分析
  • name ‘bare_metal_version‘ is not mamba_ssm安装
  • Redis|Springboot集成Redis
  • 完整版已注册,永久授权!
  • 计算机毕业设计SpringBoot+Vue.js车辆管理系统(源码+文档+PPT+讲解)
  • C语言学习笔记-进阶(7)字符串函数3
  • Day04 模拟原生开发app过程 Androidstudio+逍遥模拟器
  • 安装完flash-attn,使用时报错undefined symbol
  • vocabulary is from your listening,other speaking and your thought.
  • Spark数据倾斜深度解析与实战解决方案
  • Java并发编程面试题:内存模型(6题)
  • 一步步解析 HTTPS
  • C/C++蓝桥杯算法真题打卡(Day4)
  • 【愚公系列】《Python网络爬虫从入门到精通》045-Charles的SSL证书的安装
  • 高品质汉化解锁!