Three.js to draw a static 3D sphere tutorial

Source: Internet
Author: User

Three.js is actually a 3D JS engine, where the powerful is that the JS framework is not based on jquery to write. So, what should we pay attention to when we write this article that draws a 3D sphere? Let me just list the

1. Scene.

What is the scene, to put it simply, the scene is a canvas, we are to canvas above to achieve the 3D effect of the screen. The scene and the container, the camera is closely related, we take the film for example, if we need to play a costume drama of the tear force scene, then, we need one of the props is a camera.

2. Container

is the div that hosts the sphere, for example, if we want to act, then the venue for acting, like a beautiful place.

3. Camera

Simply put, what do you mean by looking at the sphere from the screen? Actually very simple, you think you are playing a biochemical crisis, is not the first person? Then you see the different monsters, with different perspectives to see, then the results, there will be differences, this is the role of the camera.

4. The actor (in this case, the sphere)

This is too easy, but I'm not necessarily talking about a sphere, maybe a cube, maybe a complex shape, THREE. JS provides a lot of "library", these libraries can draw different shapes of objects, for beginners, to understand this is enough. The

code

Code is not particularly complex, and you can understand it in a hierarchical way, such as adding a camera to the scene, which is a layer of cover, and there are some proprietary words in English,

<div id= "Container" ></div>   <script>     //Set the size of the scene   
  var width = 400;
    var height = 300;
      //Set some parameters for the camera.
    var view_angle = 45;
    aspect = width / height;
    near = 0.1;
    far = 10000;
      //set up containers     var  $container  = $ ("#container");       //A new webgl  rendering, and camera     var renderer =  New three.
Webglrenderer ();     var camera =         new three.
Perspectivecamera (        view_angle, aspect, near, far         );     var scene = new three.
Scene ();
      //Add the camera to the scene     scene.add (camera);
      camera.position.z = 300;
      renderer.setsize (width, height);
      //additional DOM elements      $container. Append (renderer.domelement);       //Set the value of the sphere     var radius = 50, segemnt
 = 16, rings = 16;       var spherematerial = new three.
Meshlambertmaterial ({ color: 0xcc0000 });       var sphere = new three. Mesh (        new three. Spheregeometry (radius,segemnt,rings),         spherematerial  
       );
     sphere.geometry.verticesNeedUpdate = true;
    sphere.geometry.normalsNeedUpdate = true;
      scene.add (Sphere);       var pointlight = new three.
Pointlight (0XFFFFFF);
      pointLight.position.x = 10;
    pointLight.position.y = 50;
    pointLight.position.z = 150;
      scene.add (pointlight);             //paint     renderer.render (Scene,
 camera);   </script>


  
Final effect

As I am also a beginner, so to everyone's help is also very limited, but I will work hard, often to learn from their own three.js some of the experience to share it!





a little tutorial on how to use Three.js

Yesterday looked at Three.js this thing, as a 3D engine, he is still very powerful. There is a tutorial on the official website that is not very detailed. http://aerotwist.com/tutorials/getting-started-with-three-js/

The content of the nonsense is more, there is a person to do the translation here http://blog.csdn.net/webgl_/article/details/6424749

In GitHub above can obtain the source code of three.js, direct download zip on the line https://github.com/mrdoob/three.js/

At present, Google Chrome does not support the WebGL of XP, opera recently launched an experimental version of WEBGL to support XP, users can use XP to search.

The directory is probably like this, build is loaded with a compressed JS code, use Three.js only need to include./build/three.js on it./build/custom should provide you with a number of scripts that you can customize.

/docs provides a very rudimentary API document, but it can be looked at.
/examples There are a lot of examples, this is very good. One of the more is WEBGL opening and canvas the beginning of the file, is probably provided, the two technologies to achieve comparison, WEBGL faster than canvas 100 times times (unofficial statistics), after all, WebGL use hardware acceleration, it is obvious to see Canvas_geometry_ Hierarchy.ht and webgl_geometry_hierarchy.html These two examples./examples subfolders below are the scripts for some elements such as./js/shaderextra.js is some ready-made shader code, Can be directly used, or some font and statistics fps scripts, three.js inside the use of./js/stats.js this script to do some statistical work. There are some models or something.
/src inside is the source code.
/gui inside should be some graphical things, not carefully studied.
./utils inside are some tools that should be scripts for compiling connections or something.

The use of three.js is simpler, a major camera, a major scene, a render (which translates into a renderer, canvas,webgl,svg, etc.), other light, Materials,object, The shrimp are all for the good.

First of all, this camera, three.js camera There are many kinds, the simplest is called the Perspectivecamera perspective camera, or the vision camera, so as to create a new instance.

var camera, scene, renderer;
var windowhalfx = WINDOW.INNERWIDTH/2;
var windowhalfy = WINDOW.INNERHEIGHT/2;
Camera = new Three.perspectivecamera (Window.innerwidth/window.innerheight, 10000);
CAMERA.POSITION.Z = 1000;


The four properties are the camera's view cone angle, the aspect ratio of the viewport, the camera's proximal section (Front clipping Plane) and the remote section (back clipping Plane), which determines the camera's cone of sight.

The position.z is perpendicular to the screen, that is, the distance from the cutting plane.

Of course, you can also adjust the direction of the camera by Camera.lookat, but it is not necessary here.


To Earth for example, assuming that the earth is vertically placed, the angle of view cone is very small, can only see the image around the equator, near the cutting edge of the far side can only see the old world or the Western Hemisphere, this said also not very clear, their own change parameters to try, on the line.

Scene is very simple to create, directly new, and then just add a variety of things to the sence inside, just like this.

var camera, scene, renderer;
Scene = new Three.scene ();
Scene.add (camera);


Next is to add some object, here we use a thing called mesh, using this mesh model, it is easier to build simple geometry, ball ah, cylinder ah, what, of course, the modal also need Maya and other professional tools.

The structure of the mesh is like this


var mesh;
Mesh = new Three.mesh (new Three.spheregeometry), new three.meshbasicmaterial ({Map:three.imageutils.loadt Exture ('./land_ocean_ice_cloud_2048.jpg '), overdraw:true}));
Scene.add (mesh);


The function to create a sphere is this

THERE. Spheregeomrtry (radius, segments, rings) The first parameter is the RADIUS, the latter two can be understood as the fine degree of the sphere, the higher the value of the ball is more round, you can adjust the latter two parameters of their own experience.

THERE. Meshbasicmaterial () is the material, if you want a monochrome material can be like this

var spherematerial = new Three.meshlambertmaterial (
{
color:0xcc0000
});


Using a custom Picture It is, then, that Overdraw is an overly-rendered switch and it doesn't matter now.

var spherematerial = new Three.meshbasicmaterial (
{
map:three.imageutils.loadtexture ('./land_ocean_ice_clo Ud_2048.jpg '), Overdraw:true
});


Finally set the mesh position, add it to the scene can be

MESH.POSITION.Y =-;
mesh.rotation.x =-math.pi/180;
Scene.add (mesh);


The creation of the renderer is also very simple, here is the use of a canvasrenderer, the final need to add render dom to the container of the last, the simple point is, through the renderer 3D image output to the page.

As for the introduction of the DOM structure here http://www.w3school.com.cn/htmldom/is a tree-shaped structure, the AppendChild method is to add the DOM in the parameter to the last node of the specified node.

var container = document.getElementById (' container ');
renderer = new Three.canvasrenderer ();
Renderer.setsize (Window.innerwidth, window.innerheight);
Container.appendchild (renderer.domelement);


loop rendering, to achieve the dynamic of 3D graphics needs to constantly change the position of camera, through continuous rendering to achieve the effect of animation

Render method to realize the conversion of perspective,

Animate method to implement loop rendering,

The principle is infinite recursive call, requestanimationframe This function is very good, interested can look at the source code.

Stats.update () is the unused tube for updating FPS.

function animate ()  {       
 requestanimationframe ( animate );
        render ();
        stats.update (); &NBSP;&NBSP;&NBSP;&NBSP} function render ()  {        
camera.position.x +=  ( mousex - camera.position.x )  * 0.05;         camera.position.y +=  ( - mousey -
 camera.position.y )  * 0.05;
        camera.lookat ( scene.position );
        mesh.rotation.y -= 0.005;
        renderer.render ( scene, camera );             .} 

The


finally integrates the code so that it realizes a rotation of the earth. The two pictures used in the code can be found in the Exmples/textures

<!doctype html> 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.