Chapter 1:Create You First 3D Scene With Three.js

1,各浏览器对WebGL的支持

手机浏览器对WebGL的支持:

书的源码:https://github.com/josdirksen/learning-threejs

第一次用浏览器打开代码可能无法正常显示,好像要对浏览器做一些设置额。

创建第一个3D场景包括这几样东西:

<!DOCTYPE html>

<html>

<head>
    <title>Example 01.06 - Screen size change</title>
    <script type="text/javascript" src="../libs/three.js"></script>
    <script type="text/javascript" src="../libs/stats.js"></script>//shows the frames per second(fps) for animation
    <script type="text/javascript" src="../libs/dat.gui.js"></script>//allows you to very easily create a simple user interface component that can change variables in your code
    <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">

    var camera;
    var scene;
    var renderer;

    // once everything is loaded, we run our Three.js stuff.
    function init() {
    
        var stats = initStats();

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        // create a camera, which defines where we‘re looking at.
        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // create a render and set the size
        renderer = new THREE.WebGLRenderer();

        renderer.setClearColor(new THREE.Color(0xEEEEEE, 1.0));
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;

        // create the ground plane
        var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1);
        var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true;

        // rotate and position the plane
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // add the plane to the scene
        scene.add(plane);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.castShadow = true;

        // position the cube
        cube.position.x = -4;
        cube.position.y = 3;
        cube.position.z = 0;

        // add the cube to the scene
        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);

        // position the sphere
        sphere.position.x = 20;
        sphere.position.y = 0;
        sphere.position.z = 2;
        sphere.castShadow = true;

        // add the sphere to the scene
        scene.add(sphere);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // add subtle ambient lighting
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);

        // add spotlight for the shadows
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // add the output of the renderer to the html element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // call the render function
        var step = 0;

        var controls = new function () {
            this.rotationSpeed = 0.02;
            this.bouncingSpeed = 0.03;
        };

        var gui = new dat.GUI();
        gui.add(controls, ‘rotationSpeed‘, 0, 0.5);
        gui.add(controls, ‘bouncingSpeed‘, 0, 0.5);

        render();

        function render() {
            stats.update();
            // rotate the cube around its axes
            cube.rotation.x += controls.rotationSpeed;
            cube.rotation.y += controls.rotationSpeed;
            cube.rotation.z += controls.rotationSpeed;

            // bounce the sphere up and down
            step += controls.bouncingSpeed;
            sphere.position.x = 20 + ( 10 * (Math.cos(step)));
            sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));

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

        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;
        }
    }
    function onResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    }

    window.onload = init;

    // listen to the resize events
    window.addEventListener(‘resize‘, onResize, false);

</script>
</body>
</html>
时间: 2024-08-09 22:02:42

Chapter 1:Create You First 3D Scene With Three.js的相关文章

泡泡一分钟:Project AutoVision - Localization and 3D Scene Perception for an Autonomous Vehicle with a Multi-Camera System

Project AutoVision - Localization and 3D Scene Perception for an Autonomous Vehicle with a Multi-Camera System https://arxiv.org/abs/1809.05477 Abstract: Project AutoVision aims to develop localization and 3D scene perception capabilities for a self-

网页3D效果库Three.js初窥

网页3D效果库Three.js初窥 背景 一直想研究下web页面的3D效果,最后选择了一个比较的成熟的框架Three.js下手 ThreeJs官网 ThreeJs-github; 接下来我会陆续翻译 Three.js官网的文档,部分文字和代码为我个人添加. 第一部分:three.js介绍 创建场景 这部分的目标是为Three.js做一个简单的介绍,我们会以创建一个场景,一个旋转的立方里开始,文章的结尾会有一个可运行的完整示例为你解惑. 开始之前 在你使用Three.js之前,你需要在你的电脑上建

leaflet开源地图库源码研读(五)——extend、Object.create、fn.bind分析(Util.js文件)

一.extend:扩展对象的属性 1 var Util = { 2 extend: function (dest) { 3 var i, j, len, src; 4 for (j = 1, len = arguments.length; j < len; j++) { 5 src = arguments[j]; 6 for (i in src) { 7 dest[i] = src[i]; 8 } 9 } 10 return dest; 11 } 12 } 可以,看出extend方法里有2个fo

[Tools] Create a Simple CLI Tool in Node.js with CAC

Command-line tools can help you with all sorts of tasks. This lesson covers the very basics of setting up a CLI tool in Node.js by creating your project with npm, setting up your bin script, and using CAC to parse a single argument. Create a new proj

javascript 3d网页 示例 ( three.js 初探 七)

1 完整代码下载 https://pan.baidu.com/s/1JJyVcP2KqXsd5G6eaYpgHQ 提取码 3fzt (压缩包名: 2020-4-5-demo.zip) 2 图片展示 3 主要代码 1 "use strict" 2 3 class InitControl{ 4 5 constructor(View, Three){ 6 this.view = View; 7 this.three = Three; 8 this.target = {object: null

3D视觉差---原生js+css

1 <!doctype html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> <style> * { padding: 0; margin: 0; }body { background: #42509a; } u

WPF中的3D Wireframe

原文:WPF中的3D Wireframe WPF不支持画三维线,但开发人员提供了ScreenSpaceLines3D 类用于实现这个功能.我已经在程序中实现并成功显示3D Wireframe,并能够进行3D Solid和3D Wireframe的切换. 我在熟悉这个类的基础上,自己定义了3D Wireframe xml文件的格式,用于保存3D Wireframe数据. 格式如下: <Wireframe>? <ScreenSpaceLines3D??? Form="Generic

2.CCGridAction(3D效果),3D反转特效,凸透镜特效,液体特效,3D翻页特效,水波纹特效,3D晃动的特效,扭曲旋转特效,波动特效,3D波动特效

 1 类图组织 2 实例 CCSprite * spr = CCSprite::create("HelloWorld.png"); spr->setPosition(ccp(winSize.width/2,winSize.height/2)); addChild(spr); //GridAction //CCFlipX3D * action = CCFlipX3D::create(2); //CCFlipY3D * action = CCFlipY3D::create(2);

3.CCFadeOutTRTiles,部落格效果,跳动的方块特效,3D瓷砖晃动特效,破碎的3D瓷砖特效,瓷砖洗牌特效,分多行消失特效,分多列消失特效

 1 TiledGrid3D //TiledGrid3D //CCFadeOutTRTiles * action = CCFadeOutTRTiles::create(2, CCSize(20,20)); //CCFadeOutBLTiles * action = CCFadeOutBLTiles::create(2, CCSize(20,20)); //CCJumpTiles3D * action = CCJumpTiles3D::create(2, CCSize(4,4),20,20);