[Front-end knowledge] Three learning log (1) - a simple attempt of Three.js

Three Learning Log (1) - A simple attempt at Three.js

Three.js is a lightweight 3D graphics library written in JavaScript, which can render 3D scenes in the browser. In the process of learning Three.js, establishing a basic scenario is an important first step. By setting up components such as cameras, scenes, and renderers, you can create a simple 3D scene. After establishing a basic scene, you can enrich the scene effect by adding models, materials, light sources and other elements. In addition, the requestAnimationFrame method can be used to animate the scene and achieve animation effects.

1. Try Three.js simply

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learn Three.js</title>
    <!-- 引入three,下载地址参考:http://www.webgl3d.cn/pages/aac9ab/#%E7%89%B9%E5%AE%9A%E7%89%88%E6%9C%ACthree-js%E6%96%87%E4%BB%B6%E5%8C%85%E4%B8%8B%E8%BD%BD -->
    <script src="../build/three.js"></script>
</head>

<body>
    <script>
        // 任意调用API,为了检测three.js是否引入成功
        console.log(THREE.Scene);
        // 创建3D场景对象Scene
        const scene = new THREE.Scene();
        // 创建一个长方体几何对象Geometry
        const geometry = new THREE.BoxGeometry(100, 100, 100);
        // 创建一个材质对象Material(MeshBasicMaterial 为网格基础材质)
        const material = new THREE.MeshBasicMaterial({
      
      
            color: 0xff0000,//0xff0000设置材质颜色为红色
        });
        // 创建物体:网格模型(Mesh为网格模型)
        // 两个参数分别为上面创建的几何体geometry、材质material
        const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        // 设置网格模型在三维空间中的位置坐标,默认是坐标原点
        mesh.position.set(0, 10, 0);
        // 构建好物体后,将物体添加到场景中
        scene.add(mesh);
        // 至此,我们的物体已经添加到场景中,但我们并不能立即看到构建的物体,还需要通过虚拟相机进行渲染
        // 实例化一个透视投影相机对象
        const camera = new THREE.PerspectiveCamera();
        // 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000:远裁截面
        // const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
        // 根据需要设置相机位置具体值
        camera.position.set(200, 200, 200);
        //相机观察目标指向Threejs 3D空间中某个位置
        camera.lookAt(0, 0, 0); //坐标原点
        // camera.lookAt(mesh.position);//指向mesh对应的位置
        // 定义相机输出画布的尺寸(单位:像素px)
        const width = 800; //宽度
        const height = 500; //高度
        // 创建渲染器对象
        const renderer = new THREE.WebGLRenderer();
        // 设置渲染器宽高
        renderer.setSize(width, height);
        // 通过渲染器,将场景和相机进行结合、渲染,得到一个Canvas元素
        renderer.render(scene, camera); //执行渲染操作
        // 将渲染结果加入页面中
        document.body.appendChild(renderer.domElement);
    </script>
</body>

</html>

2. Effect display
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42919342/article/details/132975993