【threejs】每天一個小案例講解:創建基本的3D場景

代碼倉

GitHub - TiffanyHoo/three_practices: Learning three.js together!

可自行clone,無需安裝依賴,直接liver-server運行/直接打開chapter01中的html文件

運行效果圖

知識要點

核心運行代碼

<!DOCTYPE html><html><head><title>Example 03.02 - point Light</title><script type="text/javascript" src="../libs/three.js"></script><script type="text/javascript" src="../libs/stats.js"></script><script type="text/javascript" src="../libs/dat.gui.js"></script><style>body {/* set margin to 0 and overflow to hidden, to go fullscreen */margin: 0;overflow: hidden;}</style>
</head><body><div id="Stats-output"></div><!-- Div which will hold the Output --><div id="WebGL-output"></div><!-- Javascript code that runs our Three.js examples --><script type="text/javascript">// once everything is loaded, we run our Three.js stuff.function init() {// create a scene, that will hold all our elements such as objects, cameras and lights.var scene = new THREE.Scene();// create a camera, which defines where we're looking at.var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);// create a render and set the sizevar renderer = new THREE.WebGLRenderer();// var renderer = new THREE.WebGLRenderer({alpha: true});/*** alpha: true 啟用透明度支持* !!!透明度沒有生效* 1.因為沒有啟用渲染器透明度支持* 2.沒有正確使用setClearColor方法兩個參數*   renderer.setClearColor(new THREE.Color(0xEEEEEE, 1.0));*   透明度 (0-1) 0 完全透明 1完全不透明**/renderer.setClearColor(new THREE.Color(0xEEEEEE, 1.0));renderer.setSize(window.innerWidth, window.innerHeight);// renderer.shadowMapEnabled = true;// 啟用陰影貼圖:用于在3D場景中生成和渲染物體的陰影// create the ground planevar planeGeometry = new THREE.PlaneGeometry(60, 20, 20, 20);var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff });var plane = new THREE.Mesh(planeGeometry, planeMaterial);plane.receiveShadow = true; // 接收陰影// rotate and position the planeplane.rotation.x = -0.5 * Math.PI;plane.position.x = 15;plane.position.y = 0;plane.position.z = 0;// add the plane to the scenescene.add(plane);// create a cubevar cubeGeometry = new THREE.BoxGeometry(4, 4, 4);var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff7777 });// MeshLambertMaterial 基于Lambert反射模型的材質,適用于不發光且沒有高光的物體(表面粗糙、沒有明顯反光)。它支持顏色、貼圖、透明度等屬性。var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);cube.castShadow = true; // 投射陰影// position the cubecube.position.x = -4;cube.position.y = 3;cube.position.z = 0;// add the cube to the scenescene.add(cube);var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);var sphereMaterial = new THREE.MeshLambertMaterial({ color: 0x7777ff });var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);// position the spheresphere.position.x = 20;sphere.position.y = 0;sphere.position.z = 2;sphere.castShadow = true;// add the sphere to the scenescene.add(sphere);// position and point the camera to the center of the scenecamera.position.x = -25;camera.position.y = 30;camera.position.z = 25;camera.lookAt(new THREE.Vector3(10, 0, 0));// 添加光源// add subtle ambient lightingvar ambiColor = "#0c0c0c";var ambientLight = new THREE.AmbientLight(ambiColor);scene.add(ambientLight);// add spotlight for the shadowsvar spotLight = new THREE.SpotLight(0xffffff);console.log(spotLight.position);spotLight.position.set(-40, 60, -10);spotLight.castShadow = true;console.log(spotLight);console.log(spotLight.target); // 默認(0,0,0)console.log(spotLight.shadow); // undefined shadow屬性是在r128之后引入的// scene.add( spotLight );var pointColor = "#ccffcc";var pointLight = new THREE.PointLight(pointColor); // 無陰影pointLight.distance = 100; // 0 無限遠 光線強度不隨距離增加而減弱scene.add(pointLight);// add a small sphere simulating the pointlightvar sphereLight = new THREE.SphereGeometry(0.2);var sphereLightMaterial = new THREE.MeshBasicMaterial({ color: 0xac6c25 });var sphereLightMesh = new THREE.Mesh(sphereLight, sphereLightMaterial);sphereLightMesh.castShadow = true;sphereLightMesh.position = new THREE.Vector3(3, 0, 3);scene.add(sphereLightMesh);// const directionalLight = new THREE.DirectionalLight(0xffffff, 1);// directionalLight.position.set(-40, 60, -10);// directionalLight.castShadow = true;// scene.add(directionalLight);// add the output of the renderer to the html elementdocument.getElementById("WebGL-output").appendChild(renderer.domElement);// call the render functionvar step = 0;// used to determine the switch point for the light animationvar invert = 1;var phase = 0;var controls = new function () {this.rotationSpeed = 0.03;this.bouncingSpeed = 0.03;this.ambientColor = ambiColor;this.pointColor = pointColor;this.intensity = 1;this.distance = 100;};var gui = new dat.GUI();gui.addColor(controls, 'ambientColor').onChange(function (e) {ambientLight.color = new THREE.Color(e);});gui.addColor(controls, 'pointColor').onChange(function (e) {pointLight.color = new THREE.Color(e);});gui.add(controls, 'intensity', 0, 3).onChange(function (e) {pointLight.intensity = e;});gui.add(controls, 'distance', 0, 100).onChange(function (e) {pointLight.distance = e;});var stats = initStats();render();function render() {stats.update();// rotate the cube around its axescube.rotation.x += controls.rotationSpeed;cube.rotation.y += controls.rotationSpeed;cube.rotation.z += controls.rotationSpeed;// bounce the sphere up and downstep += controls.bouncingSpeed;sphere.position.x = 20 + (10 * (Math.cos(step)));sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));// move the light simulationif (phase > 2 * Math.PI) {invert = invert * -1;phase -= 2 * Math.PI;} else {phase += controls.rotationSpeed;}sphereLightMesh.position.z = +(7 * (Math.sin(phase)));sphereLightMesh.position.x = +(14 * (Math.cos(phase)));sphereLightMesh.position.y = 5;if (invert < 0) {var pivot = 14;sphereLightMesh.position.x = (invert * (sphereLightMesh.position.x - pivot)) + pivot;}pointLight.position.copy(sphereLightMesh.position);// render using requestAnimationFramerequestAnimationFrame(render);renderer.render(scene, camera);}function initStats() {var stats = new Stats();stats.setMode(0); // 0: fps, 1: ms// Align top-leftstats.domElement.style.position = 'absolute';stats.domElement.style.left = '0px';stats.domElement.style.top = '0px';document.getElementById("Stats-output").appendChild(stats.domElement);return stats;}}window.onload = init</script>
</body></html>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/84047.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/84047.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/84047.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

微軟PowerBI考試 PL300-使用 Power BI 準備數據以供分析【提供練習數據】

微軟PowerBI考試 PL300-使用 Power BI 準備數據以供分析 您將了解如何使用 Power Query 從不同的數據源中提取數據&#xff0c;選擇存儲模式和連接性類型。 您還將了解在對數據進行建模之前&#xff0c;如何分析、清理數據以及將數據加載到 Power BI 中。 在 Power BI 中獲取…

Linux與Windows切換使用Obsidian,出現 unexplained changes 問題的解決

如果你的Obsidian文檔在Linux與Windows間來回切換&#xff0c;可能會涉及到文件的保存換行符問題&#xff0c;但這樣的話就容易導致一個問題&#xff0c;那就是內容無差異&#xff0c;Obsidian卻提示unexplained changes&#xff0c;Windows系統下的解決方法如下&#xff0c;找…

Python爬蟲-爬取各省份各年份高考分數線數據,進行數據分析

前言 本文是該專欄的第60篇,后面會持續分享python爬蟲干貨知識,記得關注。 本文,筆者將基于Python爬蟲,爬取各省份歷年以來的“各年份高考分數線”進行數據分析。 廢話不多說,具體實現思路和詳細邏輯,筆者將在正文結合完整代碼進行詳細介紹。接下來,跟著筆者直接往下看…

基于cornerstone3D的dicom影像瀏覽器 第三十章 心胸比例測量工具CTRTool

文章目錄 前言一、實現過程1. 學習CobbAngleTool源碼2. 新建CTRTool.js文件3. 重寫constructor函數4. 重寫defaultGetTextLines函數5. 增加_calculateLength函數6. 重寫_calculateCachedStats函數7. 重寫renderAnnotation函數 二、使用步驟1.引入庫2. 添加到cornerstoneTools3.…

[嵌入式AI從0開始到入土]18_Ascend C算子開發環境(S5賽季)

[嵌入式AI從0開始到入土]嵌入式AI系列教程 注&#xff1a;等我摸完魚再把鏈接補上 可以關注我的B站號工具人呵呵的個人空間&#xff0c;后期會考慮出視頻教程&#xff0c;務必催更&#xff0c;以防我變身鴿王。 第1期 昇騰Altas 200 DK上手 第2期 下載昇騰案例并運行 第3期 官…

《前端面試題:JavaScript 閉包深度解析》

JavaScript 閉包深度解析&#xff1a;從原理到高級應用 一、閉包的本質與核心概念 閉包&#xff08;Closure&#xff09;是 JavaScript 中最強大且最常被誤解的概念之一。理解閉包不僅是掌握 JavaScript 的關鍵&#xff0c;也是區分初級和高級開發者的重要標志。 1. 什么是閉…

【FPGA開發】DDS信號發生器設計

一、常見IP模塊介紹 IP(IntellectualProperty)原指知識產權、著作權等&#xff0c;在IC設計領域通常被理解為實現某種功能的設計。IP模塊則是完成某種比較復雜算法或功能&#xff08;如FIR濾波器、FFT、SDRAM控制器、PCIe接口、CPU核等&#xff09;并且參數可修改的電路模塊&a…

板凳-------Mysql cookbook學習 (九--3)

4.3 使用臨時表 Drop table 語句來刪除表&#xff0c; 選擇使用create temporary table 語句&#xff0c;創建的是一張臨時表。 Create temporary table tb1_name(…列定義…) 克隆表 Create temporary table new_table like original_table 根據查詢結果建表 Create temporary…

Python Web項目打包(Wheel)與服務器部署全流程

目錄 一、本地開發環境準備二、創建setup.py打包配置三、創建WSGI入口文件四、打包生成Wheel文件五、服務器端部署流程1. 傳輸文件到服務器2. 服務器環境準備3. 配置生產環境變量4. 使用Gunicorn啟動服務 六、高級部署方案&#xff08;Systemd服務&#xff09;1. 創建Systemd服…

c++ 基于openssl MD5用法

基于openssl MD5用法 #include <iostream> #include <openssl/md5.h> using namespace std; int main(int argc, char* argv[]) { cout << "Test Hash!" << endl; unsigned char data[] "測試md5數據"; unsigned char out[1024…

如何通過外網訪問內網服務器?怎么讓互聯網上連接本地局域網的網址

服務器作為一個數據終端&#xff0c;是很多企事業單位不可獲缺的重要設備&#xff0c;多數公司本地都會有部署服務器供測試或部署一些網絡項目使用。有人說服務器就是計算機&#xff0c;其實這種說法不是很準確。準確的說服務器算是計算機的一種&#xff0c;它的作用是管理計算…

安裝Openstack

基本按照Ubuntu官網的指南來安裝&#xff0c;使用單節點模式&#xff0c;官網步驟參見網址&#xff1a;https://ubuntu.com/openstack/install 系統為Ubuntu 24.04.2&#xff0c;全新安裝. Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 6.11.0-24-generic x86_64)kaiexperiment…

?Kafka與RabbitMQ的核心區別

?1.設計目標與適用場景? ?Kafka?&#xff1a;專注于高吞吐量的分布式流處理平臺&#xff0c;適合處理大數據流&#xff08;如日志收集、實時數據分析&#xff09;&#xff0c;強調消息的順序性和擴展性。?? ?RabbitMQ?&#xff1a;作為消息中間件&#xff0c;側重于消…

深入理解 Spring Cache 及其核心注解

一、Spring Cache 概述? Spring Cache 并不是一個具體的緩存實現方案&#xff0c;而是一套抽象的緩存規范。它支持多種緩存技術&#xff0c;如 Ehcache、Redis、Caffeine 等&#xff0c;開發者可以根據項目需求靈活選擇合適的緩存技術。其核心思想是通過在方法上添加注解&…

STM32H562----------串口通信(UART)

1、串口介紹 1.1、 數據通信概念 在單片機中我們常用的通信方式有 USART、IIC、SPI、CAN、USB 等; 1、數據通信方式 根據數據通信方式可分為串行通信和并行通信兩種,如下圖: 串行通信基本特征是數據逐位順序依次傳輸,優點:傳輸線少成本低,抗干擾能力強可用于遠距離傳…

20-Oracle 23 ai free Database Sharding-特性驗證

對于Oracle 23ai Sharding 新特性的驗證腳本&#xff0c;目標是涵蓋其核心改進和新增功能。基于 Oracle 23ai 的 Sharding 特性總結&#xff08;Raft 協議、True Cache、Vector等&#xff09;&#xff0c;結合常見場景驗證。 通過SQL腳本驗證這些特性。例如&#xff1a; 1.基于…

? 常用 Java HTTP 客戶端匯總及使用示例

在 Java 開發中,HTTP 客戶端是與服務端交互的關鍵組件。隨著技術發展,出現了多種 HTTP 客戶端庫,本文匯總了常用的 Java HTTP 客戶端,介紹其特點、適用場景,并附上簡單使用示例,方便開發者快速選擇和上手。 1.常用 HTTP 客戶端一覽 名稱簡介特點HttpClient(JDK 自帶)Ja…

MCP(Model Context Protocol)與提示詞撰寫

隨著大模型&#xff08;LLM&#xff09;在復雜任務中的普及&#xff0c;如何讓模型高效調用外部工具和數據成為關鍵挑戰。傳統函數調用&#xff08;Function Calling&#xff09;依賴開發者手動封裝 API&#xff0c;而 MCP&#xff08;Model Context Protocol&#xff09; 通過…

RootSIFT的目標定位,opencvsharp。

首先截取匹配模板&#xff0c;然后使用rootsift特征匹配&#xff0c;最后定位目標。 對于微弱變化&#xff0c;還是能夠識別定位的&#xff0c;對于傳統算法來說已經不錯了。 目標定位效果&#xff1a; 使用的模板圖片。 using OpenCvSharp; using OpenCvSharp.Features2D;u…

Appium如何支持ios真機測試

ios模擬器上UI自動化測試 以appiumwebdriverio為例&#xff0c;詳細介紹如何在模擬器上安裝和測試app。在使用ios模擬器前&#xff0c;需要安裝xcode&#xff0c;創建和啟動一個simulator。simulator創建好后&#xff0c;就可以使用xcrun simctl命令安裝被測應用并開始測試了。…