Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

threejs webgl2.0

作者:ares丶技术魂   发布日期:2025-07-07   浏览:98

// threejs webgl2.0 示例代码

// 引入 Three.js 库
import * as THREE from 'three';

// 创建场景
const scene = new THREE.Scene();

// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// 创建渲染器,并启用 WebGL2
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance', logarithmicDepthBuffer: true, context: getContext() });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 获取 WebGL2 上下文
function getContext() {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('webgl2', { antialias: true, powerPreference: 'high-performance' });
    if (!context) {
        console.error('WebGL2 is not supported by your browser.');
        return null;
    }
    return context;
}

// 创建一个几何体和材质
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

// 创建网格并添加到场景中
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 动画函数
function animate() {
    requestAnimationFrame(animate);

    // 旋转立方体
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    // 渲染场景
    renderer.render(scene, camera);
}

// 开始动画
animate();

解释说明:

  1. Three.js 库引入:通过 import 语句引入 Three.js 库。
  2. 创建场景、相机和渲染器:分别创建了场景 (scene)、透视相机 (camera) 和渲染器 (renderer)。特别地,渲染器启用了 WebGL2 支持。
  3. 获取 WebGL2 上下文:通过 getContext 函数确保浏览器支持 WebGL2。
  4. 创建几何体和材质:创建了一个简单的立方体几何体和基本材质。
  5. 创建网格并添加到场景:将几何体和材质组合成网格对象 (cube) 并添加到场景中。
  6. 动画函数:使用 requestAnimationFrame 实现动画效果,使立方体不断旋转,并在每一帧调用 renderer.render 渲染场景。

这段代码展示了如何使用 Three.js 和 WebGL2 创建一个简单的旋转立方体动画。

上一篇:js 对象过滤

下一篇:js require用法

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站