HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Tuần 9: vẽ 3D</title> <script src="../asets/glsim.js"></script> <!-- load the OpenGL 1.1 simulation code --> <script> let frameNumber = 0, camera; function drawShpere(radius, slices, stacks) { var i, j; for (j = 0; j < stacks; j++) { var latitude1 = (Math.PI / stacks) * j - Math.PI / 2; var latitude2 = (Math.PI / stacks) * (j + 1) - Math.PI / 2; var sinLat1 = Math.sin(latitude1); var cosLat1 = Math.cos(latitude1); var sinLat2 = Math.sin(latitude2); var cosLat2 = Math.cos(latitude2); glBegin(GL_QUAD_STRIP); for (i = 0; i <= slices; i++) { var longitude = (2 * Math.PI / slices) * i; var sinLong = Math.sin(longitude); var cosLong = Math.cos(longitude); var x1 = cosLong * cosLat1; var y1 = sinLong * cosLat1; var z1 = sinLat1; var x2 = cosLong * cosLat2; var y2 = sinLong * cosLat2; var z2 = sinLat2; glNormal3d(x2, y2, z2); glVertex3d(radius * x2, radius * y2, radius * z2); glNormal3d(x1, y1, z1); glVertex3d(radius * x1, radius * y1, radius * z1); } glEnd(); } } function transform() { frameNumber += 1; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera.apply(); glPushMatrix(); glRotatef(frameNumber,0,0,1); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0.8, 0.3, 0, 1]); drawShpere(3,32,16); //Vẽ mặt trời glRotatef(-2*frameNumber,0,0,1); glTranslatef(8,0,0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0, 0, 0.5, 1]); drawShpere(2,32,16); //Vẽ trái đất glRotatef(-2*frameNumber,0,0,1); glTranslatef(4,0,0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0.3, 0.3, 0.3, 1]); drawShpere(1,32,16); //Vẽ mặt trăng glPopMatrix(); } function draw() { setInterval(transform, 1000 / 24) } function initGL() { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); glClearColor(0, 0, 0, 1); glColor3f(0, 0, 0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0, 0, 0.5, 1]); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [0.2, 0.2, 0.2, 1]); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 16); glLightfv(GL_LIGHT0, GL_SPECULAR, [1, 1, 1, 1]); // Light-0 với ánh sáng trắng glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.2, 0.2, 0.2, 1]); // mức sáng ở phía rìa glPolygonOffset(1, 1); } function init() { // Called by <body onload="init()">, when the page has loaded. try { glsimUse("glcanvas"); // OpenGL will draw to the canvas with id="glcanvas". } catch (e) { document.getElementById("canvas-holder").innerHTML = "Sorry, an error occured:<br>" + e; return; } initGL(); camera = new Camera(); camera.setScale(10); camera.installTrackball(transform); draw(); } window.onload = init; </script> </head> <body> <h3>Tuần 9: vẽ 3D </h3> <noscript> <p><b>Sorry, this page requires JavaScript!</b></p> </noscript> <div id="canvas-holder"> <canvas id="glcanvas" width="600" height="500" style="border: solid 1px gray;"></canvas> </div> </body> </html>