Threejs入门-实操篇

在前一篇文章(Threejs入门-安装教程-CSDN博客)中,我们介绍了threejs官方的安装流程,对于同学们学习中比较繁琐复杂,本文介绍在实际学习中使用的方法。

1、安装开发中需要的js库。

win+R输入cmd进入控制台,命令进入学习中的项目文件夹。

npm命令安装threejs,npm i three,该方法会安装最新的threejs。

0ce7966fe7ec41f4bc093aaae4cb9b52.png

项目文件夹会多出以下文件内容:

c8d8512afbdd4890895e423b81563e8a.png

2、使用vscode打开这个工作文件夹。

在开发中需要使用的js库都在以下文件中。仍然需要拓展插件five serves(GitHub - yandeu/five-server: ⚡ Development Server with Live Reload Capability. (Maintained Fork of Live Server))可以在vscode插件市场直接下载。

f03a1a534160467593c1bc59da1484ee.png

新建一个index.html网页文件。

将html与js代码写在一个文件中。

这是需要注意的注意点:

这段代码对应这一句代码       import * as THREE from 'three';

    <script type="importmap">
        {
            "imports":{
                "three":"./node_modules/three/build/three.module.js"
            }
        }
    </script>

(注意逗号,后面没有多余的路径项,就把逗号去掉)

 

如果不清楚路径怎么寻找的同学,可以去学习文件路径的知识。

3、代码+结果。

结合官方中,需要对浏览器的兼容性检测,加入一些代码。

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

<head>
    <meta charset="utf-8">
    <title>My first three.js app</title>
    <style>
        body {
            margin: 0;
        }
    </style>
</head>

<body>
    <!-- 下面的代码是路径代替,对应下面的script中的import的简短路径
    注意每个路径之间的逗号,最后不加逗号  -->
    <script type="importmap">
        {
            "imports":{
                "three":"./node_modules/three/build/three.module.js",
                "three/addons/": "./node_modules/three/examples/jsm/" 
            }
        }
    </script>

    <script type="module">
        import * as THREE from 'three';
        import WebGL from 'three/addons/capabilities/WebGL.js';

        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        const geometry = new THREE.BoxGeometry(1, 1, 1);
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        scene.add(cube);


        camera.position.z = 5;

        function animate() {
            requestAnimationFrame(animate);

            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;

            renderer.render(scene, camera);
        }

        if (WebGL.isWebGLAvailable()) {

            // Initiate function or other initializations here
            animate();
        } else {

            const warning = WebGL.getWebGLErrorMessage();
            document.getElementById('container').appendChild(warning);

        }

    </script>
</body>

</html>

这时就可以实现在一个项目文件夹下建立多个网页了,不需要安装多个构建工具。

 

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值