WebGL은 Javascript의 보다 복잡한 API 중 하나로 기록되어 있습니다. 대화형 모든 것에 흥미를 느끼는 웹 개발자로서 저는 WebGL의 MDN 문서를 자세히 살펴보기로 결정했습니다. 저는 WebGL의 많은 어려움을 추상화하는 Three.js로 작업해 보았지만, 그 내용을 공개하지 않을 수 없었습니다!
이 심층 분석의 목표는 문서를 더 간단한 용어로 설명할 수 있을 만큼 문서를 이해할 수 있는지 확인하는 것이었습니다. 면책조항 — 저는 Three.js로 작업해 왔으며 3D 그래픽 용어와 패턴에 대해 약간의 지식을 가지고 있습니다. 이러한 개념이 어떤 식으로든 적용된다면 반드시 설명하겠습니다.
먼저 삼각형을 만드는 데 집중하겠습니다. 그 이유는 webGL 설정에 필요한 부분에 대한 이해를 돕기 위함입니다.
어떤 내용이 다루어질지 알아보기 위해 우리가 거치게 될 단계는 다음과 같습니다.
HTML 캔버스 설정
WebGL 컨텍스트 가져오기
캔버스 색상을 지우고 새 색상으로 설정
삼각형 (x,y) 좌표 배열 만들기
정점 및 조각 셰이더 코드 추가
셰이더 코드 처리 및 컴파일
webGL 프로그램 만들기
버퍼 생성 및 webGL 프로그램 바인딩
프로그램 이용하기
GPU 정보를 CPU에 연결
삼각형 그리기
HTML 캔버스 설정
- "RenderTriangle"이라는 폴더를 만듭니다
- 해당 폴더에 index.html과 main.js 파일을 생성하세요
index.html 파일 내에 다음 코드를 추가하세요.
index.js
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <canvas id="canvas"></canvas> <script src="main.js"></script>
은 WebGL 컨텍스트 렌더링을 위한 진입점입니다
기본 HTML 코드를 설정하고 main.js 파일을 링크합니다.
main.js 파일에서 webGL 콘텐츠를 렌더링하기 위해 캔버스 ID에 액세스합니다.
HTML 캔버스 준비
main.js 파일 내에 HTML 캔버스를 준비하는 다음 코드를 추가하세요.
main.js
// get canvas const canvas = document.getElementById("canvas"); // set width and height of canvas canvas.width = window.innerWidth; canvas.height = window.innerHeight; // get the webgl context const gl = canvas.getContext("webgl2");
ID로 HTML 캔버스를 가져와서 "canvas"라는 변수에 저장합니다(어떤 이름이든 사용할 수 있음).
window.innerWidth 및 window.innerHeight에 액세스하여 캔버스의 canvas.width 및 canvas.height 속성을 설정합니다. . 이렇게 하면 렌더링된 디스플레이가 브라우저 창의 크기로 설정됩니다.
canvas.getContext(“webgl2”)를 사용하여 WebGL 컨텍스트를 가져와서 “gl”이라는 변수에 저장합니다.
클리어 컬러
main.js
gl.clearColor(0.1, 0.2, 0.3, 1.0); gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
webGL 프로그램을 작성하기 전에 캔버스의 배경색을 설정해야 합니다. WebGL에는 이를 실현하는 두 가지 방법이 있습니다.
clearColor() — 특정 배경색을 설정하는 메서드입니다. WebGL을 HTML 캔버스에 렌더링할 때 CSS가 배경을 검정색으로 설정하기 때문에 "clearColor"라고 합니다. clearColor()를 호출하면 기본 색상이 지워지고 원하는 색상이 설정됩니다. 아래에서 확인할 수 있습니다.
참고: clearColor()에는 4개의 매개변수(r, g, b, a)가 있습니다
clear() — clearColor()가 호출되고 명시적인 배경색이 설정된 후
**clear()**는 버퍼를 사전 설정된 값으로 "지우거나 재설정"하기 위해 호출되어야 합니다(버퍼는 색상 및 깊이 정보를 위한 임시 저장소입니다).
clear() 메소드는 그리기 메소드 중 하나로 실제로 색상을 렌더링하는 메소드입니다. clear() 메서드를 호출하지 않으면 캔버스에 clearColor가 표시되지 않습니다. clear() 매개변수 옵션은
gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT 또는 gl.STENCIL_BUFFER_BIT입니다.
아래 코드에서는 여러 매개변수를 추가하여 다양한 시나리오에서 재설정할 수 있습니다.
gl.DEPTH_BUFFER_BIT — 픽셀 깊이 정보에 대한 버퍼를 나타냅니다
gl.COLOR_BUFFER_BIT — 픽셀 색상 정보에 대한 버퍼를 나타냅니다
삼각형 좌표 설정
main.js
// set position coordinates for shape const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];
배경이 설정되면 삼각형을 만드는 데 필요한 좌표를 설정할 수 있습니다. 좌표는 (x, y) 좌표로 배열에 저장됩니다.
아래 배열은 3점 좌표를 담고 있습니다. 이 점들이 연결되어 삼각형을 형성합니다.
0.0, -1.0
0.0 , 1.0
1.0, 1.0
정점 및 조각 셰이더 추가
main.js
const vertexShader = `#version 300 es precision mediump float; in vec2 position; void main() { gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w } `; const fragmentShader = `#version 300 es precision mediump float; out vec4 color; void main () { color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a } `;
삼각형 좌표에 대한 변수를 생성한 후 셰이더를 설정할 수 있습니다.
A shader is a program written in OpenGL ES Shading Language. The program takes position and color information about each vertice point. This information is what’s needed to render geometry.
There are two types of shaders functions that are needed to draw webgl content, the vertex shader and fragment shader
*vertex shader *— The vertex shader function uses position information to render each pixel. Per every render, the vertex shader function runs on each vertex. The vertex shader then transforms each vertex from it’s original coordinates to WebGL coordinates. Each transformed vertex is then saved to the gl_Position variable in the vertex shader program.
*fragment shader *— The fragment shader function is called once for every pixel on a shape to be drawn. This occurs after the vertex shader runs. The fragment shader determines how the color of each pixel and “texel (pixel within a texture)” should be applied. The fragment shader color is saved in the gl_FragColor variable in the fragment shader program.
In the code above we are creating both a vertexShader and fragmentShader constant and storing the shader code in them. The Book of Shaders is a great resource for learning how to write GLSL code.
Processing the Vertex and Fragment Shaders
main.js
// process vertex shader const shader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(shader, vertexShader); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(vertexShader)); } // process fragment shader const shader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(shader, fragmentShader); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(fragmentShader)); }
Now that we wrote the shader code (GLSL), we need to create the shader. The shader code still needs to compile. To do this we call the following functions:
createShader() — This creates the shader within the WebGL context
shaderSource() — This takes the GLSL source code that we wrote and sets it into the webGLShader object that was created with createShader.
compileShader() — This compiles the GLSL shader program into data for the WebGLProgram.
The code above processes the vertex and fragment shaders to eventually compile into the WebGLProgram.
Note: An if conditional is added to check if both shaders have compiled properly. If not, an info log will appear. Debugging can be tricky in WebGL so adding these checks is a must.
Creating a WebGL Program
main.js
const program = gl.createProgram(); // Attach pre-existing shaders gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { const info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n${info}"; }
Let’s review the code above:
After compiling the vertexShader and fragmentShader, we can now create a WebGLProgram. A WebGLProgram is an object that holds the compiled vertexShader and fragmentShader.
createProgram() — Creates and initializes the WebGLProgram
attachShader() — This method attaches the shader to the webGLProgram
linkProgram() — This method links the program object with the shader objects
Lastly, we need to make a conditional check to see if the program is running properly. We do this with the gl.getProgramParameter.
Create and Bind the Buffers
Now that the WebGL Program is created and the shader programs are linked to it, it’s time to create the buffers. What are buffers?
To simplify it as much as possible, buffers are objects that store vertices and colors. Buffers don’t have any methods or properties that are accessible. Instead, the WebGL context has it’s own methods for handling buffers.
Buffer — “a temporary storage location for data that’s being moved from one place to another”
-wikipedia
We need to create a buffer so that we can store our triangle colors and vertices.
To do this we add the following:
main.js
const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null);
In the code above we’re creating a buffer (or temporary storage object) using the createBuffer() method. Then we store it in a constant. Now that we have a buffer object we need to bind it to a target. There are several different target but since we’re storing coordinates in an array we will be using the gl.ARRAY_BUFFER.
To bind the buffer to a target, we use gl.bindBuffer() and pass in the gl.ARRAY_BUFFER (target) and the buffer itself as parameters.
The next step would be to use gl.bufferData() which creates the data store. gl.bufferData() takes the following parameters:
target — gl.ARRAY_BUFFER
data — new Float32Array(triangleCoords)
usage (draw type) — gl.STATIC_DRAW
Lastly, we unbind the buffer from the target to reduce side effects.
Use Program
main.js
gl.useProgram(program);
Once the buffer creation and binding is complete, we can now call the method that sets the WebGLProgram to the rendering state.
Link GPU and CPU
As we get closer to the final step, we need to talk about attributes.
In WebGL, vertex data is stored in a special variable called attributes. attributes are only available to the javascript program and the vertex shader. To access the attributes variable we need to first get the location of the attributes from the GPU. The GPU uses an index to reference the location of the attributes.
main.js
// get index that holds the triangle position information const position = gl.getAttribLocation(obj.program, obj.gpuVariable); gl.enableVertexAttribArray(position); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(position, 2, gl.FLOAT, obj.normalize, obj.stride, obj.offset);
Let’s review the code above:
Since we’re rendering a triangle we need the index of the position variable that we set in the vertex shader. We do this using the gl.getAttribLocation() method. By passing in the WebGL program and the position variable name (from the vertex shader) we can get the position attribute’s index.
Next, we need to use the gl.enableVertexAttribArray() method and pass in the position index that we just obtained. This will enable the attributes` storage so we can access it.
We will then rebind our buffer using gl.bindBuffer() and pass in the gl.ARRAY_BUFFER and buffer parameters (the same as when we created the buffers before). Remember in the “Create and Bind the Buffers” section we set the buffer to null to avoid side effects.
When we binded the buffer to the gl.ARRAY_BUFFER we are now able to store our attributes in a specific order. gl.vertexAttribPointer() allows us to do that.
By using gl.vertexAttribPointer() we can pass in the attributes we’d like to store in a specific order. The parameters are ordered first to last.
The gl.vertexAttribPointer is a more complex concept that may take some additional research. You can think of it as a method that allows you to store your attributes in the vertex buffer object in a specific order of your choosing.
Sometimes 3D geometry already has a certain format in which the geometry information is set. vertexAttribPointer comes in handy if you need to make modifications to how that geometry information is organized.
Draw Triangle
main.js
gl.drawArrays(gl.TRIANGLES, 0, 3);
Lastly, we can use the gl.drawArrays method to render the triangle. There are other draw methods, but since our vertices are in an array, this method should be used.
gl.drawArrays() takes three parameters:
mode — which specifies the type of primitive to render. (in this case were rendering a triangle)
first — specifies the starting index in the array of vector points (our triangle coordinates). In this case it’s 0.
count — specifies the number of indices to be rendered. ( since it's a triangle we’re rendering 3 indices)
Note: For more complex geometry with a lot of vertices you can use **triangleCoords.length / 2 **to ****get how many indices your geometry has.
Finally, your triangle should be rendered to the screen! Let’s review the steps.
Set up the HTML canvas
Get the WebGL context
Clear the canvas color and set a new one
Create an array of triangle (x,y )coordinates
Add vertex and fragment shader code
Process and compile the shader code
Create a webGL program
Create and bind buffers to the webGL program
Use the program
Link the GPU information to the CPU
Draw out the triangle
The API is a complex one so there’s still a lot to learn but understanding this setup has given me a better foundation.
// Set up the HTML canvas const canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // get the webgl context const gl = canvas.getContext("webgl2"); // Clear the canvas color and set a new one gl.clearColor(0.1, 0.2, 0.3, 1.0); gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT); // Create an array of triangle (x,y )coordinates const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0]; // Add vertex and fragment shader code const vertexShader = `#version 300 es precision mediump float; in vec2 position; void main() { gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w } `; const fragmentShader = `#version 300 es precision mediump float; out vec4 color; void main () { color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a } `; // Process and compile the shader code const vShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vShader, vertexShader); gl.compileShader(vShader); if (!gl.getShaderParameter(vShader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(vertexShader)); } const fShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fShader, fragmentShader); gl.compileShader(fShader); if (!gl.getShaderParameter(fShader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(fragmentShader)); } // Create a webGL program const program = gl.createProgram(); // Link the GPU information to the CPU gl.attachShader(program, vShader); gl.attachShader(program, fShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { const info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n${info}"; } // Create and bind buffers to the webGL program const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); // Use the program gl.useProgram(program); // Link the GPU information to the CPU const position = gl.getAttribLocation(program, "position"); gl.enableVertexAttribArray(position); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(position, 2, gl.FLOAT, gl.FALSE, 0, 0); // render triangle gl.drawArrays(gl.TRIANGLES, 0, 3);
Here are some invaluable references to help understand this material better.
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
https://www.udemy.com/course/webgl-internals/
https://webglfundamentals.org/
위 내용은 WebGL 삼각형 설정 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
