Use JavaScript and WebGL to draw the Earth "translation"

Source: Internet
Author: User
Tags script tag

Use JavaScript and WebGL to draw the Earth "translation"

Original translation: Using JavaScript and WebGL to draw the Earth "translation"

WebGL is probably the most interesting of all of our known html5api, and with this API we can create cool 3D scenes in the browser. This article will give you a complete demonstration of how cool is implemented.

In particular, this tutorial will build a Planet planet model that can be rotated around like an excited person, and it may allow us to get compliments from some other programmers, well, that's all.

Get ready

In this tutorial we will use a fascinating WebGL plugin: three.js. This plugin is a bit like jquery, but it is for WebGL, which abstracts many of the complex native API access interfaces so that we can take advantage of WebGL's features more easily.

In HTML, we can introduce this plugin through a normal script tag, as follows:

<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r63/three.min.js"></script>

Here we refer to the CDN version, which can be introduced using local methods if you need to. Then we need to make sure that WebGL has something to render on it. Here we have a flexible approach: we can directly write the general Div or canvas into the HTML, or we can use JS to create and append the canvas elements into the DOM before rendering. Here we use the first easy-to-point approach, as follows:

<body><divId= "Container" Span class= "token punctuation" >> </div> <script src = "Earth.js "> </script></body>    

After adding the script tag to the DOM, our HTML section is almost complete.

Next

Tree.js itself is the tendency to make things very close to the real 3D desktop program. We have a scene where there are some things live and then browse through the camera, then some lights, special effects, rendering on the whole scene, of course they are all 3D objects themselves. The list of elements in this scene seems a bit scary, in our earth.js file, all of these elements can be used as shape variables,Javascript files are as follows:

var scene, Camera, light, renderer, Earthobject;var WIDTH= window.innerwidth - Span class= "token number" >30= Window.innerheight -30; var angle = 45= WIDTH /Height, near = 0.1 = 3000              

Some additional variables are also defined here, and the width,height variable is used to get the width and height of our canvas, and the following other variables will be used to set the position of our camera. For almost all 3D objects, all of these elements are common, both in the platform and the environment, so here we habitually write these guys together. With Three.js, however, we can easily implement it, and we'll look at how all of these elements are fused to the project at the same time.

Environment

First, we need to enable the new variables and initialize them, so that our Earth model can be displayed more dazzling. We can set the variables for each environment factor first:

var container= document.getElementById(' Container '); Camera=NewThree. Perspectivecamera(Angle, Aspect, near, far); camera. position.Set(0,0,0); scene=NewThree. Scene(); Light=NewThree. SpotLight(0xFFFFFF,1,0, Math. Pi/2,1);light.position set (40004000 1500;light.position. Set  (100038001000         

The following is a description of the execution of the above code:

    • Crawl container objects in our HTML
    • We set up the camera object with the previously declared variables (more information about how cameras works in 3D, click here)
    • Using the position.set method to set the camera location, this method needs to carry a dimension (x, Y, z) Parameter object, perhaps you have thought, we will use this camera to locate our 3D object, the 3D object in this tutorial is our earth model.
    • Next, set up our light object. If there is no light object to do the rendering, then the whole model will be the effect of a dark, so we must pay careful attention to this step. Three.js's Spotlight object has parameters that are roughly the same as our camera object, except that the first parameter of the object must be a value of 16, and then the rest of the parameters are basically the same as the camera.
    • Finally, we need to set up our Canvas object renderer. Another point to make sure is that we need to render the canvas object fully to the screen ahead of time, again emphasizing that if this step is not done, the whole canvas will be invisible and dark. We added a antialiasing effect to the canvas and added the effect as a DOM element to our original container.

Now we need to build our entire model by pasting the whole Earth in the same way we do online. The code is as follows:

var Earthgeo=NewThree. Spheregeometry(30,40,400), Earthmat=NewThree. Meshphongmaterial();var Earthmesh=NewThree. Mesh(Earthgeo, Earthmat. Set (-10000< Span class= "token punctuation") .y=5; Scene. Add (Earthmesh ; 

Here we create a mesh object, a mesh that can be used to dress up and look like the shape of the earth, and then add some geometry to the object, an appearance wrapper, or some textured material to wrap the mesh. We will also set this object to the appropriate location, as with other parameter objects, and we will add the mesh object to our scene.

Here is a sample example. There is some extra rendering, which we'll explain later. This example looks more and more close to what we want.

Blue Planet

The next interesting part is making the skin for this guy. First we'll use a diffuse map, which will make the guy look more like a map. You can add as follows:

// diffuse mapearthMat.map = THREE.ImageUtils.loadTexture(‘images/earthmap1k.jpg‘);

If you want better texture, you can try this picture, or you can go to Google to search for a picture you want. High-resolution graphs are available.

Now the model doesn't look so bad, but we can still make the whole model look more realistic by referencing a little bit of terrain. The earth has some mountains, and in order to make sure that the other planets in the solar system are distinguished, we need to use the bump map (bump maps), in the 3D model, the bump map is black and white, using the sharp white to highlight the uneven parts of the image (for example, in our example: mountains).

// bump mapearthMat.bumpMap = THREE.ImageUtils.loadTexture(‘images/elev_bump_16ka.jpg‘);earthMat.bumpScale = 8;

Using the above picture we almost achieved the effect, once again stressed that the use of Google search "Earth bump map" will be a lot of choices, but if you feel bad, you can click on this connection. Running the above code, we will see the following effect:

Let It Go!

The rest is that we add some animation to this earth model, and for this we need two new methods that we name render() andanimate()

function animate() { requestAnimationFrame(animate); render(); }

Our animate() approach is not very complex, and through our own recursive successive invocation requestAnimationFrame() methods, anmiate() we will ask our render() method to look at render() the code of the method:

functionRender(){var clock=NewThree (= clock. Getdelta.rotation.y += rotationspeed * delta< Span class= "token punctuation"; Renderer. Render (Scene;}     

Let's see what the above code does. Each time the render() method is requested, it causes the Earth model to rotate slowly on the Y axis (here you can choose to set any number of rotations, and here we use the getDelta() method to build a clock object to control the number of rotations, of course you can not use this method). The render() method then performs a cleanup of the canvas, which is an important step in preventing the canvas from going out, and it will render our scene (and all other objects in the scene object) and our camera object.

At last

Of course, having a drag-and-drop operation will make our Earth model experience even better, Orbitcontrols.js is a script that can provide a mouse-driven rotational effect for our Earth model, and it's also not difficult to add some stars or clouds to our stratosphere as the background of the Earth model, and if you're not too troublesome, you can even use WebGL's shader (shaders) for your star The ball adds a stratosphere.

Running the code, you can see a sample of the final demo in Codepen as follows:

View the effect by holding down the mouse drag and scrolling the mouse wheel (or click here to Demo

End

WebGL and Three.js are becoming more challenging because they occasionally ask us to do our work with scenes, canvases, and camera like 3D artists, and the end result is something that is impressive. If you focus on this technique, you can create some interesting possibilities by using 3D features in your browser. If you stick to it, you'll probably get some extraordinary results soon.

Original address: Building the Earth with WebGL and JavaScript

Use JavaScript and WebGL to draw the Earth "translation"

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.