3D graphics in browsers have been a hot topic since they were first introduced. But if you want to create an application using pure WebGL, it takes a long time. That's why some really useful libraries have emerged recently. Three.js is one of the most popular, and in this series, I'll show you how to best use it to create stunning 3D experiences for your users.
Before we begin, I do expect you to have a basic understanding of 3D space before starting this tutorial, as I will not be explaining coordinates, vectors, etc.
Step 1: Preparation
First, create three files: index.html
, main.js
, and style.css
. Now, download Three.js (the entire zip file with examples and source code, or a separate JavaScript file, your choice). Now, open index.html
and insert the following code:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="./style.css"> <script src="./three.js"></script> </head> <body> <script src="./main.js"></script> </body> </html>
That's all you need in this file. Just declarations of scripts and stylesheets. All the magic will happen in main.js
, but before we can do that, we need one more trick to make the application look better. Open style.css
and insert the following code:
canvas { position: fixed; top: 0; left: 0; }
This will position the canvas in the top left corner because body
will have 8px margins by default. Now we can move on to the JavaScript code.
Step 2: Scene and Renderer
Three.js uses the concept of display lists. This means that all objects are stored in a list and then drawn to the screen.
Three.js uses the concept of display lists. This means that all objects are stored in a list and then drawn to the screen. In this case, it's a THREE.Scene
object. You need to add any objects you want to draw on the screen to the scene. You can have as many scenes as you like, but a renderer can only draw one scene at a time (of course you can switch the displayed scenes).
The renderer simply draws everything in the scene onto the WebGL canvas. Three.js also supports drawing on SVG or 2D Canvas, but we will focus on WebGL.
First, let's store the width and height of the window in variables, we will use it later:
var width = window.innerWidth; var height = window.innerHeight;
Now define the renderer and scene:
var renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(width, height); document.body.appendChild(renderer.domElement); var scene = new THREE.Scene;
The first line defines the WebGL renderer. You can pass the renderer options in the first parameter as a map. Here, we set antialias
to true since we want the edges of the object to be smooth, not jagged.
The second line sets the renderer size to the size of the window, and in the third line we add the canvas
element of the renderer to the document (you can also use a library to do this, e.g. jQuery: $( 'body').append(renderer.domElement)
).
The last definition scene does not require parameters.
Step 3: Cube
Now let's add what we want to draw. Let it be a cube, as it is the simplest 3D object. In Three.js, the objects drawn on the screen are called grids. Each mesh must have its own geometry and materials. Geometry is a set of points that need to be connected to create an object. A material is just paint (or painting, but that's not the topic of this tutorial) that covers an object. So, let's create our cube. Fortunately, there are some helper functions in Three.js for creating primitives (simple shapes):
var cubeGeometry = new THREE.CubeGeometry(100, 100, 100); var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0x1ec876 }); var cube = new THREE.Mesh(cubeGeometry, cubeMaterial); cube.rotation.y = Math.PI * 45 / 180; scene.add(cube);
As you can see, first we create the geometry. Parameters define the size of the cube: width, height and depth.
Next, we define the material of the cube. There are some material types in Three.js, but this time we will use THREE.MeshLambertMaterial
because we want some lighting later (this material uses Lambert's algorithm for lighting calculations). You can pass the options in the first argument as a map, the same as for renderers - this is pretty much the rule for more complex objects in Three.js. Here we only use color, which is passed as a hexadecimal number.
In the third line, we create a mesh using the previously created geometry and material. Next, we rotate the cube 45 degrees on the Y axis to make it look better. We have to change degrees to radians, which is handled via an equation you might remember from high school physics class: Math.PI * 45 / 180
. Finally, the cube is added to the scene.
Now you can open index.html
in your browser to see the results, but you won't see anything because the scene hasn't been rendered yet.
Step 4: Camera!
To render something, first we need to add a camera to the scene so that the renderer knows from which angle the content should be rendered. There are several types of cameras in Three.js, but you'll probably only use THREE.PerspectiveCamera
. This type of camera presents a scene of the world as we see it. Let's create one:
var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);
“要渲染某些内容,首先我们需要将相机添加到场景中,以便渲染器知道应该从哪个角度渲染内容。”
创建相机比我们迄今为止所做的其他事情要复杂一些。第一个参数定义 FOV(视野),即从相机所在位置可以看到的角度。 45 度的 FOV 看起来很自然。接下来,我们定义相机的比率。这始终是渲染器的宽度除以高度,除非您想实现一些特殊效果。最后两个数字定义了对象与要绘制的相机的距离。
现在我们必须稍微向后和向上移动相机,因为在 Three.js 中创建的所有对象都将其位置设置在场景中间(x: 0, y: 0, z: 0)默认:
camera.position.y = 160; camera.position.z = 400;
z
坐标在观看者的方向上为正,因此具有较高 z
位置的对象会显得离您更近(在这种情况下,由于我们移动了相机,所有对象都会显得更远)来自您)。
现在,让我们将相机添加到场景并渲染它:
scene.add(camera); renderer.render(scene, camera);
添加相机就像添加立方体一样。下一行使用该相机渲染场景。现在您可以打开浏览器,您应该看到以下内容:
您应该只能看到立方体的顶部。这是因为我们将相机向上移动,但它仍然看起来在它的正前方。这个问题可以通过让相机知道它应该看什么位置来解决。在设置相机位置的行之后添加此行:
camera.lookAt(cube.position);
传入的唯一参数是相机将看到的位置。现在,场景看起来更好了,但立方体仍然是黑色,无论您在创建立方体时设置了什么颜色:
第 5 步: 灯!
立方体是黑色的,因为场景中没有灯光,所以它就像一个完全黑的房间。您会看到白色背景,因为除了立方体之外没有任何东西可以绘制。为了避免这种情况,我们将使用一种称为天空盒的技术。基本上,我们将添加一个大立方体来显示场景的背景(如果是开放空间,通常是一些远处的地形)。那么,让我们创建这个盒子。此代码应位于 renderer.render
调用之前:
var skyboxGeometry = new THREE.CubeGeometry(10000, 10000, 10000); var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide }); var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial); scene.add(skybox);
此代码与创建多维数据集的代码类似。但这一次的几何形状要大得多。我们还使用了 THREE.MeshBasicMaterial
因为我们不需要照亮天空盒。另外,请注意传递给材料的附加参数:side: THREE.BackSide
。由于立方体将从内部显示,因此我们必须更改绘制的侧面(通常,Three.js 只绘制外墙)。
现在渲染的场景是全黑的。为了解决这个问题,我们必须向场景添加灯光。我们将使用 THREE.PointLight
,它像灯泡一样发出光。在天空盒后添加这些行:
var pointLight = new THREE.PointLight(0xffffff); pointLight.position.set(0, 300, 200); scene.add(pointLight);
如您所见,我们创建了白色的点光源,然后将其位置设置为向上和向后一点,以照亮立方体的正面和顶部。最后,灯光像任何其他对象一样添加到场景中。打开浏览器,您应该会看到一个彩色阴影立方体:
但是立方体仍然很无聊。让我们为其添加一些动作。
第 6 步: 行动!
现在我们将为场景添加一些运动。让我们让立方体绕 Y 轴旋转。但首先,我们必须改变渲染场景的方式。一次 renderer.render
调用,渲染场景的当前状态一次。因此,即使我们以某种方式为立方体设置动画,我们也不会看到它移动。要改变这一点,我们必须将渲染循环添加到我们的应用程序中。这可以使用专门为此目的创建的 renderAnimationFrame
函数来实现。大多数主要浏览器都支持它,对于那些不支持它的浏览器,Three.js 附带了自己的 polyfill。那么,让我们改变一下:
renderer.render(scene, camera);
对此:
function render() { renderer.render(scene, camera); requestAnimationFrame(render); } render();
实际上,那里没有循环,因为它会冻结浏览器。 requestAnimationFrame
函数的行为有点像 setTimeout
,但它会在浏览器准备就绪时调用该函数。因此,显示的场景没有任何变化,立方体仍然没有移动。让我们解决这个问题。 Three.js自带了THREE.Clock
,可以用来实现对象的平滑动画。首先在render
函数定义之前进行初始化:
var clock = new THREE.Clock;
现在,每次调用 clock.getDelta
时,它都会返回自上次调用以来的时间(以毫秒为单位)。这可以用来旋转立方体,如下所示:
cube.rotation.y -= clock.getDelta();
在 render
函数中的 renderer.render
和 requestAnimationFrame
调用之间添加此行。它只是减去立方体在 Y 轴上旋转所花费的时间(记住它以弧度为单位)来顺时针旋转立方体。现在打开浏览器,您应该看到立方体顺时针平稳旋转。
结论
在本系列的这一部分中,您学习了如何准备场景、添加对象和灯光以及如何为事物设置动画。您可以尝试该应用程序,添加更多或不同的对象、灯光。由你决定。下次我将向您展示如何使用纹理以及如何使用粒子创建一些漂亮的效果。如果遇到任何问题,请不要忘记查看文档。
The above is the detailed content of Basic introduction: WebGL development with Three.js. For more information, please follow other related articles on the PHP Chinese website!

译者 | 李睿审校 | 孙淑娟随着Python越来越受欢迎,其局限性也越来越明显。一方面,编写Python应用程序并将其分发给没有安装Python的人员可能非常困难。解决这一问题的最常见方法是将程序与其所有支持库和文件以及Python运行时打包在一起。有一些工具可以做到这一点,例如PyInstaller,但它们需要大量的缓存才能正常工作。更重要的是,通常可以从生成的包中提取Python程序的源代码。在某些情况下,这会破坏交易。第三方项目Nuitka提供了一个激进的解决方案。它将Python程序编

ChatGPT 目前彻底改变了开发代码的方式,然而,大多数软件开发人员和数据专家仍然没有使用 ChatGPT 来改进和简化他们的工作。这就是为什么我在这里概述 5 个不同的功能,以提高我们的日常工作速度和质量。我们可以在日常工作中使用它们。现在,我们一起来了解一下吧。注意:切勿在 ChatGPT 中使用关键代码或信息。01.生成项目代码的框架从头开始构建新项目时,ChatGPT 是我的秘密武器。只需几个提示,它就可以生成我需要的代码框架,包括我选择的技术、框架和版本。它不仅为我节省了至少一个小时

今天这篇文章的重点是使用 ChatGPT API 创建私人语音 Chatbot Web 应用程序。目的是探索和发现人工智能的更多潜在用例和商业机会。我将逐步指导您完成开发过程,以确保您理解并可以复制自己的过程。为什么需要不是每个人都欢迎基于打字的服务,想象一下仍在学习写作技巧的孩子或无法在屏幕上正确看到单词的老年人。基于语音的 AI Chatbot 是解决这个问题的方法,就像它如何帮助我的孩子要求他的语音 Chatbot 给他读睡前故事一样。鉴于现有可用的助手选项,例如,苹果的 Siri 和亚马

测试时自适应(Test-TimeAdaptation,TTA)方法在测试阶段指导模型进行快速无监督/自监督学习,是当前用于提升深度模型分布外泛化能力的一种强有效工具。然而在动态开放场景中,稳定性不足仍是现有TTA方法的一大短板,严重阻碍了其实际部署。为此,来自华南理工大学、腾讯AILab及新加坡国立大学的研究团队,从统一的角度对现有TTA方法在动态场景下不稳定原因进行分析,指出依赖于Batch的归一化层是导致不稳定的关键原因之一,另外测试数据流中某些具有噪声/大规模梯度的样本

哈喽,大家好。之前给大家分享过摔倒识别、打架识别,今天以摔倒识别为例,我们看看能不能完全交给ChatGPT来做。让ChatGPT来做这件事,最核心的是如何向ChatGPT提问,把问题一股脑的直接丢给ChatGPT,如:用 Python 写个摔倒检测代码 是不可取的, 而是要像挤牙膏一样,一点一点引导ChatGPT得到准确的答案,从而才能真正让ChatGPT提高我们解决问题的效率。今天分享的摔倒识别案例,与ChatGPT对话的思路清晰,代码可用度高,按照GPT返回的结果完全可以开

自 2020 年以来,内容开发领域已经感受到人工智能工具的存在。1.Jasper AI网址:https://www.jasper.ai在可用的 AI 文案写作工具中,Jasper 作为那些寻求通过内容生成赚钱的人来讲,它是经济实惠且高效的选择之一。该工具精通短格式和长格式内容均能完成。Jasper 拥有一系列功能,包括无需切换到模板即可快速生成内容的命令、用于创建文章的高效长格式编辑器,以及包含有助于创建各种类型内容的向导的内容工作流,例如,博客文章、销售文案和重写。Jasper Chat 是该

1970年,机器人专家森政弘(MasahiroMori)首次描述了「恐怖谷」的影响,这一概念对机器人领域产生了巨大影响。「恐怖谷」效应描述了当人类看到类似人类的物体,特别是机器人时所表现出的积极和消极反应。恐怖谷效应理论认为,机器人的外观和动作越像人,我们对它的同理心就越强。然而,在某些时候,机器人或虚拟人物变得过于逼真,但又不那么像人时,我们大脑的视觉处理系统就会被混淆。最终,我们会深深地陷入一种对机器人非常消极的情绪状态里。森政弘的假设指出:由于机器人与人类在外表、动作上相似,所以人类亦会对

好嘞,今天我们继续剖析下Python里的类。[[441842]]先前我们定义类的时候,使用到了构造函数,在Python里的构造函数书写比较特殊,他是一个特殊的函数__init__,其实在类里,除了构造函数还有很多其他格式为__XXX__的函数,另外也有一些__xx__的属性。下面我们一一说下:构造函数Python里所有类的构造函数都是__init__,其中根据我们的需求,构造函数又分为有参构造函数和无惨构造函数。如果当前没有定义构造函数,那么系统会自动生成一个无参空的构造函数。例如:在有继承关系


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),