精选文章 带有Three.js的WebGL –第4课

带有Three.js的WebGL –第4课

作者:cukengwei3786 时间: 2021-02-05 09:38:23
cukengwei3786 2021-02-05 09:38:23
【摘要】WebGL With Three.js – Lesson 4 Today we continue our lessons for those who study webgl, and today we will show you how to add 3D text on the scene, how to extrude two-dimensional shapes, we also wi...
带有Three.js的WebGL –第4课1
带有Three.js的WebGL –第4课2

WebGL With Three.js – Lesson 4 Today we continue our lessons for those who study webgl, and today we will show you how to add 3D text on the scene, how to extrude two-dimensional shapes, we also will consider how to load ready 3D models into the scene using the OBJLoader. It seems to be a difficult process, but it is not – the code for loading 3D models is fairly simple.

WebGL with Three.js –第4课今天,我们继续为学习webgl的人们提供课程,今天,我们将向您展示如何在场景中添加3D文本,如何拉伸二维形状,我们还将考虑如何准备好加载使用OBJLoader将3D模型放到场景中。 这似乎是一个困难的过程,但并非如此-加载3D模型的代码非常简单。

现场演示

HTML (HTML)

Two new libraries were added into the html: font1.js and OBJLoader.js

html中添加了两个新库:font1.js和OBJLoader.js

   WebGL With Three.js - Lesson 4 | Script Tutorials   <script></script> <script></script> <script></script> <script></script> <script></script> <script></script> <script></script> 
   WebGL With Three.js - Lesson 4 | Script Tutorials   <script></script> <script></script> <script></script> <script></script> <script></script> <script></script> <script></script> 

Java脚本 (Javascript)

First, we create a simple (empty) scene (scene, camera, renderer, controls, light and ground):

首先,我们创建一个简单的(空)场景(场景,相机,渲染器,控件,灯光和地面):


// load texture
var texture = THREE.ImageUtils.loadTexture('texture.png');
texture.repeat.set(0.03, 0.03);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.anisotropy = 16;
texture.needsUpdate = true;
var lesson4 = { scene: null, camera: null, renderer: null, container: null, controls: null, clock: null, stats: null, init: function() { // Initialization // create main scene this.scene = new THREE.Scene(); var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight; // prepare camera var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000; this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR); this.scene.add(this.camera); this.camera.position.set(0, 400, 800); this.camera.lookAt(new THREE.Vector3(0,0,0)); // prepare renderer this.renderer = new THREE.WebGLRenderer({antialias:true, alpha: false}); this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); this.renderer.setClearColor(0xffffff); this.renderer.shadowMapEnabled = true; this.renderer.shadowMapSoft = true; // prepare container this.container = document.createElement('div'); document.body.appendChild(this.container); this.container.appendChild(this.renderer.domElement); // events THREEx.WindowResize(this.renderer, this.camera); // prepare controls (OrbitControls) this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.controls.target = new THREE.Vector3(0, 0, 0); // prepare clock this.clock = new THREE.Clock(); // prepare stats this.stats = new Stats(); this.stats.domElement.style.position = 'absolute'; this.stats.domElement.style.bottom = '0px'; this.stats.domElement.style.zIndex = 10; this.container.appendChild( this.stats.domElement ); // add directional light var dLight = new THREE.DirectionalLight(0xffffff); dLight.position.set(0, 1000, 0); dLight.castShadow = true; // dLight.shadowCameraVisible = true; this.scene.add(dLight); // add simple ground var groundGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1); ground = new THREE.Mesh(groundGeometry, new THREE.MeshLambertMaterial({ color: 0x4489FE, side: THREE.DoubleSide })); ground.position.y = -20; ground.rotation.x = - Math.PI / 2; ground.receiveShadow = true; this.scene.add(ground); },
};
// Animate the scene
function animate() { requestAnimationFrame(animate); render(); update();
}
// Update controls and stats
function update() { lesson4.controls.update(lesson4.clock.getDelta()); lesson4.stats.update();
}
// Render the scene
function render() { if (lesson4.renderer) { lesson4.renderer.render(lesson4.scene, lesson4.camera); }
}
// Initialize lesson on page load
function initializeLesson() { lesson4.init(); animate();
}
if (window.addEventListener) window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent) window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;

// load texture
var texture = THREE.ImageUtils.loadTexture('texture.png');
texture.repeat.set(0.03, 0.03);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.anisotropy = 16;
texture.needsUpdate = true;
var lesson4 = { scene: null, camera: null, renderer: null, container: null, controls: null, clock: null, stats: null, init: function() { // Initialization // create main scene this.scene = new THREE.Scene(); var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight; // prepare camera var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000; this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR); this.scene.add(this.camera); this.camera.position.set(0, 400, 800); this.camera.lookAt(new THREE.Vector3(0,0,0)); // prepare renderer this.renderer = new THREE.WebGLRenderer({antialias:true, alpha: false}); this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); this.renderer.setClearColor(0xffffff); this.renderer.shadowMapEnabled = true; this.renderer.shadowMapSoft = true; // prepare container this.container = document.createElement('div'); document.body.appendChild(this.container); this.container.appendChild(this.renderer.domElement); // events THREEx.WindowResize(this.renderer, this.camera); // prepare controls (OrbitControls) this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.controls.target = new THREE.Vector3(0, 0, 0); // prepare clock this.clock = new THREE.Clock(); // prepare stats this.stats = new Stats(); this.stats.domElement.style.position = 'absolute'; this.stats.domElement.style.bottom = '0px'; this.stats.domElement.style.zIndex = 10; this.container.appendChild( this.stats.domElement ); // add directional light var dLight = new THREE.DirectionalLight(0xffffff); dLight.position.set(0, 1000, 0); dLight.castShadow = true; // dLight.shadowCameraVisible = true; this.scene.add(dLight); // add simple ground var groundGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1); ground = new THREE.Mesh(groundGeometry, new THREE.MeshLambertMaterial({ color: 0x4489FE, side: THREE.DoubleSide })); ground.position.y = -20; ground.rotation.x = - Math.PI / 2; ground.receiveShadow = true; this.scene.add(ground); },
};
// Animate the scene
function animate() { requestAnimationFrame(animate); render(); update();
}
// Update controls and stats
function update() { lesson4.controls.update(lesson4.clock.getDelta()); lesson4.stats.update();
}
// Render the scene
function render() { if (lesson4.renderer) { lesson4.renderer.render(lesson4.scene, lesson4.camera); }
}
// Initialize lesson on page load
function initializeLesson() { lesson4.init(); animate();
}
if (window.addEventListener) window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent) window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;

3D文字 (3D text)

The best way to display text in 3D enviromnemt is to use a ready 3D font (for Three.js). In general, there are many websites where you can download fonts, however we need special javascript fonts (typefaced fonts). This website may help you to convert custom fonts into javascript fonts (upload your font, hit the ‘convert’, and then follow the steps until it let you download the result). However, at the time of writing this tutorial, this service was not available, so I had to use ready-made fonts to create our demonstration. To draw a three-dimensional text I prepared the following function:

在3D环境中显示文本的最佳方法是使用现成的3D字体(用于Three.js)。 通常,有很多网站可以下载字体,但是我们需要特殊的javascript字体(字体字体)。 该网站可以帮助您将自定义字体转换为javascript字体(上传字体,点击“转换”,然后按照步骤进行操作,直到可以下载结果为止)。 但是,在编写本教程时,此服务尚不可用,因此我不得不使用现成的字体来创建我们的演示。 为了绘制三维文字,我准备了以下功能:

 draw3dText: function(x, y, z, text) { // prepare text geometry var textGeometry = new THREE.TextGeometry(text, { size: 60, // Font size height: 20, // Font height (depth) font: 'droid serif', // Font family weight: 'bold', // Font weight style: 'normal', // Font style curveSegments: 1, // Amount of curve segments bevelThickness: 5, // Bevel thickness bevelSize: 5, // Bevel size bevelEnabled: true, // Enable/Disable the bevel material: 0, // Main material extrudeMaterial: 1 // Side (extrude) material }); // prepare two materials var materialFront = new THREE.MeshPhongMaterial({ map: texture, color: 0xffff00, emissive: 0x888888 }); var materialSide = new THREE.MeshPhongMaterial({ map: texture, color: 0xff00ff, emissive: 0x444444 }); // create mesh object var textMaterial = new THREE.MeshFaceMaterial([ materialFront, materialSide ]); var textMesh = new THREE.Mesh(textGeometry, textMaterial); textMesh.castShadow = true; // place the mesh in the certain position, rotate it and add to the scene textMesh.position.set(x, y, z); textMesh.rotation.x = -0.3; this.scene.add(textMesh); }
 draw3dText: function(x, y, z, text) { // prepare text geometry var textGeometry = new THREE.TextGeometry(text, { size: 60, // Font size height: 20, // Font height (depth) font: 'droid serif', // Font family weight: 'bold', // Font weight style: 'normal', // Font style curveSegments: 1, // Amount of curve segments bevelThickness: 5, // Bevel thickness bevelSize: 5, // Bevel size bevelEnabled: true, // Enable/Disable the bevel material: 0, // Main material extrudeMaterial: 1 // Side (extrude) material }); // prepare two materials var materialFront = new THREE.MeshPhongMaterial({ map: texture, color: 0xffff00, emissive: 0x888888 }); var materialSide = new THREE.MeshPhongMaterial({ map: texture, color: 0xff00ff, emissive: 0x444444 }); // create mesh object var textMaterial = new THREE.MeshFaceMaterial([ materialFront, materialSide ]); var textMesh = new THREE.Mesh(textGeometry, textMaterial); textMesh.castShadow = true; // place the mesh in the certain position, rotate it and add to the scene textMesh.position.set(x, y, z); textMesh.rotation.x = -0.3; this.scene.add(textMesh); }

Two different materials are used to different sides of the text (for the front and side).

文本的不同侧面使用了两种不同的材料(正面和侧面)。

挤压几何 (ExtrudeGeometry)

This class allows us to create three-dimensional extruded geometry from two-dimensional path shape. I drew the boat for our today’s demonstration:

此类允许我们从二维路径形状创建三维挤压几何体。 我拉船去进行今天的示范:

 drawCustomObject: function(x, y, z) { // prepare points for custom shape (ship) var objectPoints = [ new THREE.Vector2 (275, 265), new THREE.Vector2 (205, 240), new THREE.Vector2 (125, 220), new THREE.Vector2 (274, 115), new THREE.Vector2 (275, 85), new THREE.Vector2 (330, 85), new THREE.Vector2 (310, 100), new THREE.Vector2 (330, 115), new THREE.Vector2 (275, 115), new THREE.Vector2 (274, 266), new THREE.Vector2 (305, 266), new THREE.Vector2 (305, 240), new THREE.Vector2 (360, 240), new THREE.Vector2 (360, 285), new THREE.Vector2 (340, 335), new THREE.Vector2 (215, 335), new THREE.Vector2 (175, 320), new THREE.Vector2 (150, 290), new THREE.Vector2 (75, 230), new THREE.Vector2 (200, 264), new THREE.Vector2 (274, 264), ]; // prepare shape var objectShape = new THREE.Shape(objectPoints); var extrusionSettings = { amount: 20, curveSegments: 1, // Amount of curve segments bevelThickness: 5, // Bevel thickness bevelSize: 5, // Bevel size bevelEnabled: true, // Enable/Disable the bevel material: 0, // Main material extrudeMaterial: 1 // Side (extrude) material }; // prepare ship geometry var objectGeometry = new THREE.ExtrudeGeometry( objectShape, extrusionSettings ); // prepare two materials var materialFront = new THREE.MeshPhongMaterial({ map: texture, color: 0xffff00, emissive: 0x888888 }); var materialSide = new THREE.MeshPhongMaterial({ map: texture, color: 0xff00ff, emissive: 0x444444 }); // create mesh object of the ship var objectMaterial = new THREE.MeshFaceMaterial([ materialFront, materialSide ]); var objectMesh = new THREE.Mesh( objectGeometry, objectMaterial ); objectMesh.castShadow = true; // place the object in the certain position, rotate it and add to the scene objectMesh.position.set(x, y, z); objectMesh.rotation.x = Math.PI; this.scene.add(objectMesh); }
 drawCustomObject: function(x, y, z) { // prepare points for custom shape (ship) var objectPoints = [ new THREE.Vector2 (275, 265), new THREE.Vector2 (205, 240), new THREE.Vector2 (125, 220), new THREE.Vector2 (274, 115), new THREE.Vector2 (275, 85), new THREE.Vector2 (330, 85), new THREE.Vector2 (310, 100), new THREE.Vector2 (330, 115), new THREE.Vector2 (275, 115), new THREE.Vector2 (274, 266), new THREE.Vector2 (305, 266), new THREE.Vector2 (305, 240), new THREE.Vector2 (360, 240), new THREE.Vector2 (360, 285), new THREE.Vector2 (340, 335), new THREE.Vector2 (215, 335), new THREE.Vector2 (175, 320), new THREE.Vector2 (150, 290), new THREE.Vector2 (75, 230), new THREE.Vector2 (200, 264), new THREE.Vector2 (274, 264), ]; // prepare shape var objectShape = new THREE.Shape(objectPoints); var extrusionSettings = { amount: 20, curveSegments: 1, // Amount of curve segments bevelThickness: 5, // Bevel thickness bevelSize: 5, // Bevel size bevelEnabled: true, // Enable/Disable the bevel material: 0, // Main material extrudeMaterial: 1 // Side (extrude) material }; // prepare ship geometry var objectGeometry = new THREE.ExtrudeGeometry( objectShape, extrusionSettings ); // prepare two materials var materialFront = new THREE.MeshPhongMaterial({ map: texture, color: 0xffff00, emissive: 0x888888 }); var materialSide = new THREE.MeshPhongMaterial({ map: texture, color: 0xff00ff, emissive: 0x444444 }); // create mesh object of the ship var objectMaterial = new THREE.MeshFaceMaterial([ materialFront, materialSide ]); var objectMesh = new THREE.Mesh( objectGeometry, objectMaterial ); objectMesh.castShadow = true; // place the object in the certain position, rotate it and add to the scene objectMesh.position.set(x, y, z); objectMesh.rotation.x = Math.PI; this.scene.add(objectMesh); }

OBJ加载器 (OBJLoader)

I left the most interesting for the end – loading ready OBJ models. The fact that there are a huge number of ready three-dimensional objects (at various websites) that you can add into your scene, and three.js gives us this opportunity through the use of the OBJLoader class:

最后,我留下了最有趣的部分-加载现成的OBJ模型。 您可以在场景中添加很多现成的三维对象(在各个网站上),并且three.js通过使用OBJLoader类为我们提供了这一机会:

 loadObjFile: function(x, y, z) { // prepare new OBJLoader and load the 'legoBrick.obj' model var loader = new THREE.OBJLoader(); loader.load('legoBrick.obj', function(object) { // apply custom material for all children var legoMat = new THREE.MeshLambertMaterial({ color: 0x008800 }); object.traverse( function (child) { if (child instanceof THREE.Mesh) { child.material = legoMat; child.material.needsUpdate = true; } }); // place the object in the certain position, rotate, scale and add to the scene object.position.x = x; object.position.y = y; object.position.z = z; object.rotation.y = Math.PI/2; object.scale.set(40, 40, 40); lesson4.scene.add(object); }); }
 loadObjFile: function(x, y, z) { // prepare new OBJLoader and load the 'legoBrick.obj' model var loader = new THREE.OBJLoader(); loader.load('legoBrick.obj', function(object) { // apply custom material for all children var legoMat = new THREE.MeshLambertMaterial({ color: 0x008800 }); object.traverse( function (child) { if (child instanceof THREE.Mesh) { child.material = legoMat; child.material.needsUpdate = true; } }); // place the object in the certain position, rotate, scale and add to the scene object.position.x = x; object.position.y = y; object.position.z = z; object.rotation.y = Math.PI/2; object.scale.set(40, 40, 40); lesson4.scene.add(object); }); }

To import the model we just specify the address to this model, as well as the callback function. In this function we applied the custom material for it’s children.

要导入模型,我们只需指定该模型的地址以及回调函数即可。 在此功能中,我们为其子级应用了自定义材料。

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

结论 (Conclusion)

Stay tuned for new lessons and you are sure to find something new and interesting for yourself.

请继续关注新课程,您一定会发现适合自己的新事物。

翻译自: https://www.script-tutorials.com/webgl-with-three-js-lesson-4/

勿删,copyright占位
分享文章到微博
分享文章到朋友圈

上一篇:内容组织上的票数

下一篇:内存还剩余很多,却使用 swap 分区

您可能感兴趣

  • 后备寄存器_带有后备功能的跨浏览器HTML5画布

    后备寄存器 Canvas是一种相对较新HTML5技术,可提供“可编写脚本”的图像。 您可以在页面上添加元素,并使用JavaScript命令在其表面上绘制。 它非常快,可用于动作游戏和动画图表-请参阅“ 3个很棒JavaScript和Canvas示例” 。 可以使用以下代码将画布标签放置在HTML5页面上: Sorry, your browser cannot displa...

  • 10个带有PHP插件的jQuery

    结合jQuery的灵巧性和PHP提供的一些简洁功能,可以产生一些简洁的效果。 以下是许多项目中需要的10个最佳PHP + jQuery组件和教程。 1.使用PHP和查询的目录树 跟踪许多文件,使用目录树。 这是一种在保持文件固有层次的同时搜索/查看文件的好方法。 本教程将帮助您使用PHP和jQuery创建有效的目录树。 资源 2.使用PHP和查询创建一个照...

  • 好看的指示器---带有半透明背景的进度轮

    //显示进度滚轮指示器-(void)showWaiting:(UIView *)parent {int width = 32, height = 32; CGRect frame = CGRectMake(100, 200, 110, 70) ;//[parent frame]; //[[UIScreen mainScreen] applicationFrame]; int x = fram...

  • 简单的具有shell功能的web服务器(带有缓存加速访问的功能)

    一、实验目的 所选题目应该与操作系统原理相关,包含进程的控制,进程间通信,并发控制,文件操作等内容。 二、实验内容 实现了一个简单的 web服务器,其中使用了内存文件系统加快部分访问量过大的大文件的访问速度,可以减低服务器负载,内嵌了一个简单的shell模块,以协助执行一些shell命令。 主要使用了一下相关知识: 1. 内存共享区 2. 文件...

  • css3--[转载][菜单导航] 带有记忆功能的多页面跳转导航菜单

    比如A页面和B页面都有一个共同的导航,当从A跳转到B,B中的导航应该记住在A点击的那个链接跳转到B这个页面,那么B页面中的那个链接也应该是选中或者激活状态。 当时的解决方案是通过JS来实现的,当点击链接的时候,通过URL来记录导航所标注的链接,然后在新的打开的页面取得URL参数,判断导航上的那个选项为激活状态。   发现CSS3的:target选择器正好可以解决此问题  ...

  • 如何删除文件名是乱码或者带有特殊字符的文件

    今天遇到一个问题,一个文件名是“-MXV9.log”,直接用rm删除的时候就报错 [localhost]rm -MXV9.logrm: illegal option -- Mrm: illegal option -- Xrm: illegal option -- Vrm: illegal option -- 9rm: illegal option -- .rm: illegal opti...

  • Java读带有BOM的UTF-8文件乱码

    通过java写的UTF-8文件,使用Java可以正确的读,但是如果用记事本将相同的内容使用UTF-8格式保存,则在使用程序读取是会从文件中多读出一个不可见字符,多一个?实例:新建一个文本:内容为“测试BOM”的txt文本,另存为UTF-8.处理带BOM的类UnicodeReader12345678910111213141516171819202122232425262728293031323...

  • WebGL中的OpenGL着色器语言

    在webgl中,调用了OpenGL-ES-2.0的API,而在OpenGL-ES专为嵌入式设备设计,其和其它设备一样,都是使用GLSL(GL Shading Language)来编写片段程序并执行于GPU的着色器上,来完成对对象的渲染。GLSL在其中起着相当重要的作用,所以要玩好webgl,我们就得把GLSL搞懂,本文主要介绍shader的基础使用及组成。   整个管线处理过程: ...

CSDN

CSDN

中国开发者社区CSDN (Chinese Software Developer Network) 创立于1999年,致力为中国开发者提供知识传播、在线学习、职业发展等全生命周期服务。

华为云40多款云服务产品0元试用活动

免费套餐,马上领取!
带有Three.js的WebGL –第4课介绍:华为云为您免费提供带有Three.js的WebGL –第4课在博客、论坛、帮助中心等栏目的相关文章,同时还可以通过 站内搜索 查询更多带有Three.js的WebGL –第4课的相关内容。| 移动地址: 带有Three.js的WebGL –第4课 | 写博客