search
HomeWeb Front-endH5 Tutorial用HTML5画一个3D的三角形网格

本教程的主题是利用HTML5技术在2D和3D图形之间搭一座互通的桥梁(通过WebGL方式)。今天我将展示如何使用一个多边形网格绘制一个三维对象。 一个多边形网格或非结构化网格是一个集合的顶点,边缘和面孔,在3 d电脑图像和实体建模定义了一个多面体的对象的形状。通常由三角形的面孔,四边形或其他简单凸多边形,因为这样可以简化渲染,但也可能是由更一般的凹多边 形,或多边形的洞。

为了演示,我们准备了简单的三维物体——一个多维数据集和多维领域

HTML CODE

通常我们会在canvas里做一个简单的标记






Triangle mesh for 3D objects in HTML5 | Script Tutorials







<script><br> //var obj = new cube();<br> //var obj = new sphere(6);<br> var obj = new sphere(16);<br> </script>





Please use Up / Down keys to change opacity





我提取一个生成的对象初始化来:

<script><br> //var obj = new cube();<br> //var obj = new sphere(6);<br> var obj = new sphere(16);<br></script>

这意味着如果我们需要显示一个多维数据集——你必须取消第一个一行,如果你想显示一个球体与6张面孔——选择第二个变体。


JS CODE

JS的代码分为三部分:主体的代码,网格代码和转换代码

meshes.js

// get random color
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i color += letters[Math.round(Math.random() * 15)];
}
return color;
}

// prepare object
function prepareObject(o) {
o.colors = new Array();

// prepare normals
o.normals = new Array();
for (var i = 0; i o.normals[i] = [0, 0, 0];

o.colors[i] = getRandomColor();
}

// prepare centers: calculate max positions
o.center = [0, 0, 0];
for (var i = 0; i o.center[0] += o.points[i][0];
o.center[1] += o.points[i][1];
o.center[2] += o.points[i][2];
}

// prepare distances
o.distances = new Array();
for (var i = 1; i o.distances[i] = 0;
}

// calculate average center positions
o.points_number = o.points.length;
o.center[0] = o.center[0] / (o.points_number - 1);
o.center[1] = o.center[1] / (o.points_number - 1);
o.center[2] = o.center[2] / (o.points_number - 1);

o.faces_number = o.faces.length;
o.axis_x = [1, 0, 0];
o.axis_y = [0, 1, 0];
o.axis_z = [0, 0, 1];
}

// Cube object
function cube() {

// prepare points and faces for cube
this.points=[
[0,0,0],
[100,0,0],
[100,100,0],
[0,100,0],
[0,0,100],
[100,0,100],
[100,100,100],
[0,100,100],
[50,50,100],
[50,50,0],
];

this.faces=[
[0,4,5],
[0,5,1],
[1,5,6],
[1,6,2],
[2,6,7],
[2,7,3],
[3,7,4],
[3,4,0],
[8,5,4],
[8,6,5],
[8,7,6],
[8,4,7],
[9,5,4],
[9,6,5],
[9,7,6],
[9,4,7],
];

prepareObject(this);
}

// Sphere object
function sphere(n) {
var delta_angle = 2 * Math.PI / n;

// prepare vertices (points) of sphere
var vertices = [];
for (var j = 0; j for (var i = 0; i vertices[j * n + i] = [];
vertices[j * n + i][0] = 100 * Math.sin((j + 1) * delta_angle) * Math.cos(i * delta_angle);
vertices[j * n + i][1] = 100 * Math.cos((j + 1) * delta_angle);
vertices[j * n + i][2] = 100 * Math.sin((j + 1) * delta_angle) * Math.sin(i * delta_angle);
}
}
vertices[(n / 2 - 1) * n] = [];
vertices[(n / 2 - 1) * n + 1] = [];

vertices[(n / 2 - 1) * n][0] = 0;
vertices[(n / 2 - 1) * n][1] = 100;
vertices[(n / 2 - 1) * n][2] = 0;

vertices[(n / 2 - 1) * n + 1][0] = 0;
vertices[(n / 2 - 1) * n + 1][1] = -100;
vertices[(n / 2 - 1) * n + 1][2] = 0;

this.points = vertices;

// prepare faces
var faces = [];
for (var j = 0; j for (var i = 0; i faces[j * 2 * n + i] = [];
faces[j * 2 * n + i + n] = [];

faces[j * 2 * n + i][0] = j * n + i;
faces[j * 2 * n + i][1] = j * n + i + 1;
faces[j * 2 * n + i][2] = (j + 1) * n + i + 1;
faces[j * 2 * n + i + n][0] = j * n + i;
faces[j * 2 * n + i + n][1] = (j + 1) * n + i + 1;
faces[j * 2 * n + i + n][2] = (j + 1) * n + i;
}

faces[j * 2 * n + n - 1] = [];
faces[2 * n * (j + 1) - 1] = [];

faces[j * 2 * n + n - 1 ][0] = (j + 1) * n - 1;
faces[j * 2 * n + n - 1 ][1] = (j + 1) * n;
faces[j * 2 * n + n - 1 ][2] = j * n;
faces[2 * n * (j + 1) - 1][0] = (j + 1) * n - 1;
faces[2 * n * (j + 1) - 1][1] = j * n + n;
faces[2 * n * (j + 1) - 1][2] = (j + 2) * n - 1;
}
for (var i = 0; i faces[n * (n - 4) + i] = [];
faces[n * (n - 3) + i] = [];

faces[n * (n - 4) + i][0] = (n / 2 - 1) * n;
faces[n * (n - 4) + i][1] = i;
faces[n * (n - 4) + i][2] = i + 1;
faces[n * (n - 3) + i][0] = (n / 2 - 1) * n + 1;
faces[n * (n - 3) + i][1] = (n / 2 - 2) * n + i + 1;
faces[n * (n - 3) + i][2] = (n / 2 - 2) * n + i;
}

faces[n * (n - 3) - 1] = [];
faces[n * (n - 2) - 1] = [];

faces[n * (n - 3) - 1][0] = (n / 2 - 1) * n;
faces[n * (n - 3) - 1][1] = n - 1;
faces[n * (n - 3) - 1][2] = 0;
faces[n * (n - 2) - 1][0] = (n / 2 - 1) * n + 1;
faces[n * (n - 2) - 1][1] = (n / 2 - 2) * n;
faces[n * (n - 2) - 1][2] = (n / 2 - 2) * n + n - 1;

this.faces=faces;

prepareObject(this);
}

main.js

// inner variables
var canvas, ctx;
var vAlpha = 0.5;
var vShiftX = vShiftY = 0;
var distance = -700;
var vMouseSens = 0.05;
var iHalfX, iHalfY;

// initialization
function sceneInit() {
// prepare canvas and context objects
canvas = document.getElementById('scene');
ctx = canvas.getContext('2d');

iHalfX = canvas.width / 2;
iHalfY = canvas.height / 2;

// initial scale and translate
scaleObj([3, 3, 3], obj);
translateObj([-obj.center[0], -obj.center[1], -obj.center[2]],obj);
translateObj([0, 0, -1000], obj);

// attach event handlers
document.onkeydown = handleKeydown;
canvas.onmousemove = handleMousemove;

// main scene loop
setInterval(drawScene, 25);
}

// onKeyDown event handler
function handleKeydown(e) {
kCode = ((e.which) || (e.keyCode));
switch (kCode) {
case 38: vAlpha = (vAlpha case 40: vAlpha = (vAlpha >= 0.2) ? (vAlpha - 0.1) : vAlpha; break; // Down key
}
}

// onMouseMove event handler
function handleMousemove(e) {
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;

if ((x > 0) && (x 0) && (y vShiftY = vMouseSens * (x - iHalfX) / iHalfX;
vShiftX = vMouseSens * (y - iHalfY) / iHalfY;
}
}

// draw main scene function
function drawScene() {
// clear canvas
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

// set fill color, stroke color, line width and global alpha
ctx.strokeStyle = 'rgb(0,0,0)';
ctx.lineWidth = 0.5;
ctx.globalAlpha= vAlpha;

// vertical and horizontal rotate
var vP1x = getRotationPar([0, 0, -1000], [1, 0, 0], vShiftX);
var vP2x = getRotationPar([0, 0, 0], [1, 0, 0], vShiftX);
var vP1y = getRotationPar([0, 0, -1000], [0, 1, 0], vShiftY);
var vP2y = getRotationPar([0, 0, 0], [0, 1, 0], vShiftY);
rotateObj(vP1x, vP2x, obj);
rotateObj(vP1y, vP2y, obj);

// recalculate distances
for (var i = 0; i obj.distances[i] = Math.pow(obj.points[i][0],2) + Math.pow(obj.points[i][1],2) + Math.pow(obj.points[i][2], 2);
}

// prepare array with face triangles (with calculation of max distance for every face)
var iCnt = 0;
var aFaceTriangles = new Array();
for (var i = 0; i var max = obj.distances[obj.faces[i][0]];
for (var f = 1; f if (obj.distances[obj.faces[i][f]] > max)
max = obj.distances[obj.faces[i][f]];
}
aFaceTriangles[iCnt++] = {faceVertex:obj.faces[i], faceColor:obj.colors[i], distance:max};
}
aFaceTriangles.sort(sortByDistance);

// prepare array with projected points
var aPrjPoints = new Array();
for (var i = 0; i aPrjPoints[i] = project(distance, obj.points[i], iHalfX, iHalfY);
}

// draw an object (surfaces)
for (var i = 0; i
ctx.fillStyle = aFaceTriangles[i].faceColor;

// begin path
ctx.beginPath();

// face vertex index
var iFaceVertex = aFaceTriangles[i].faceVertex;

// move to initial position
ctx.moveTo(aPrjPoints[iFaceVertex[0]][0], aPrjPoints[iFaceVertex[0]][1]);

// and draw three lines (to build a triangle)
for (var z = 1; z ctx.lineTo(aPrjPoints[iFaceVertex[z]][0], aPrjPoints[iFaceVertex[z]][1]);
}

// close path, strole and fill a triangle
ctx.closePath();
ctx.stroke();
ctx.fill();
}
}

// sort function
function sortByDistance(x, y) {
return (y.distance - x.distance);
}

// initialization
if (window.attachEvent) {
window.attachEvent('onload', sceneInit);
} else {
if (window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
sceneInit();
};
window.onload = newonload;
} else {
window.onload = sceneInit;
}
}



查看演示:http://www.script-tutorials.com/demos/319/index.html

下载:用HTML5画一个3D的三角形网格.zip


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool