css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!-- 来自 Learning Three.js -->
<script src="https://unpkg.com/three"></script>
<script src="https://unpkg.com/stats.js"></script>
<script src="https://cdn.bootcss.com/dat-gui/0.6.5/dat.gui.min.js"></script>

<div id="Stats-output">
</div>
<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>
            
          
!
            
              body {
  /* set margin to 0 and overflow to hidden, to go fullscreen */
  margin: 0;
  overflow: hidden;
}
            
          
!
            
              // 加载完所有资源后,再执行 Three.js 相关的东西
    function init() {
        // 创始化 stats 插件
        var stats = initStats();
        // 创建一个场景,它能放置所有元素,如网格对象、摄像机、灯光等
        var scene = new THREE.Scene();
      
        // 创建一个摄像机
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // 创建一个渲染器,并设置其清除颜色和大小
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColor(new THREE.Color(0xEEEEEE));
        renderer.setSize(window.innerWidth, window.innerHeight);


        document.addEventListener('mousedown', onDocumentMouseDown, false);
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        // 创建平面
        var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1);
        var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);


        // 旋转并定位平面
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // 添加平面到场景
        scene.add(plane);

        // 创建一个立方体
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);


        // 设置立方体的位置
        cube.position.x = -2;
        cube.position.y = 3;
        cube.position.z = 0;

        // 添加立方体至场景
        scene.add(cube);

        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshLambertMaterial({color: 0x7777ff});
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

        // 设置球体的位置
        sphere.position.x = 20;
        sphere.position.y = 0;
        sphere.position.z = 2;
        // 添加球体至场景
        scene.add(sphere);
        
        // 创建圆柱体
        var cylinderGeometry = new THREE.CylinderGeometry(2, 2, 20);
        var cylinderMaterial = new THREE.MeshLambertMaterial({color: 0x77ff77});
        var cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial);

        cylinder.position.set(0, 0, 1);

        scene.add(cylinder);


        // 设置摄像机的位置和朝向
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 添加环境光,用于提亮场景
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        
        // 添加聚光灯
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);

        scene.add(spotLight);

        // 将渲染器的输出(canvas)插入到特定 DOM 元素下
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // call the render function
        var step = 0;
        var scalingStep = 0;
        
      
        // 设置 dat.gui 插件
        var controls = new function () {
            this.rotationSpeed = 0.02;
            this.bouncingSpeed = 0.03;
            this.scalingSpeed = 0.03;
            this.showRay = false;
        };

        var gui = new dat.GUI();
        gui.add(controls, 'rotationSpeed', 0, 0.5);
        gui.add(controls, 'bouncingSpeed', 0, 0.5);
        gui.add(controls, 'scalingSpeed', 0, 0.5);
        gui.add(controls, 'showRay').onChange(function (e) {
            if (tube) scene.remove(tube)
        });
        render();

        function render() {
            stats.update();
            // 绕其自身中心的坐标轴旋转
            cube.rotation.x += controls.rotationSpeed;
            cube.rotation.y += controls.rotationSpeed;
            cube.rotation.z += controls.rotationSpeed;

            // 球体跳动
            step += controls.bouncingSpeed;
            sphere.position.x = 20 + ( 10 * (Math.cos(step)));
            sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));

            // 缩放圆柱体

            scalingStep += controls.scalingSpeed;
            var scaleX = Math.abs(Math.sin(scalingStep / 4));
            var scaleY = Math.abs(Math.cos(scalingStep / 5));
            var scaleZ = Math.abs(Math.sin(scalingStep / 7));
            cylinder.scale.set(scaleX, scaleY, scaleZ);

            // render using requestAnimationFrame
            renderer.render(scene, camera);
            requestAnimationFrame(render);

        }

        var tube;

        function onDocumentMouseDown(event) {

            var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1, -( event.clientY / window.innerHeight ) * 2 + 1, 0.5);
            vector = vector.unproject(camera);

            var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

            var intersects = raycaster.intersectObjects([sphere, cylinder, cube]);
            console.log(intersects)
            // console.log(intersects.length)
            if (intersects.length > 0) {

                // console.log(intersects[0]);

                intersects[0].object.material.transparent = true;
                intersects[0].object.material.opacity = 0.1;
            }
        }

        function onDocumentMouseMove(event) {
            if (controls.showRay) {
                var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1, -( event.clientY / window.innerHeight ) * 2 + 1, 0.5);
                vector = vector.unproject(camera);

                var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
                var intersects = raycaster.intersectObjects([sphere, cylinder, cube]);

                if (intersects.length > 0) {

                    var points = [];
                    points.push(new THREE.Vector3(-30, 39.8, 30));
                    points.push(intersects[0].point);

                    var mat = new THREE.MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: 0.6});
                    var tubeGeometry = new THREE.TubeGeometry(new THREE.SplineCurve3(points), 60, 0.001);

                    if (tube) scene.remove(tube);

                    if (controls.showRay) {
                        tube = new THREE.Mesh(tubeGeometry, mat);
                        scene.add(tube);
                    }
                }
            }
        }

        function initStats() {

            var stats = new Stats();

            stats.setMode(0); // 0: fps, 1: ms

            // Align top-left
            stats.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;
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console