当前位置:网站首页>[webgl] simple tutorial
[webgl] simple tutorial
2022-04-21 22:02:00 【Xiao Shen Yue】
The first 1 Chapter - Introduce
WebGL It solves the problem that users in the page Draw and render 3D graphics The function of , And enables users to communicate with Three dimensional graphics interact into For the possibility , This technology will play an important role in developing user-friendly and intuitive interfaces in the next generation . In the next few years ,WebGL Technology will be widely used in mobile terminals of electronic devices , Include Flat 、 Mobile devices , therefore ,WebGL Technology learning is particularly important .
It's about the technology stack
- HTML、HTML5
- JavaScript
- GLSL ES Language
The first 2 Chapter - First time to know WebGL
2.1 Draw a graph manually 
Implementation steps
- Add a canvas element
- Get the canvas element based on webgl Context object
- Using the API Realize graphics rendering
Code
<body>
<canvas id="cvs" width="200" height="200" style="border: dashed 1px red">
Your browser does not support canvas elements
</canvas>
<script type="text/javascript"> // Get canvas elements var cvs = document.getElementById('cvs') // Get the context object of the element var gl = cvs.getContext('webgl') // Set the color of the drawing fill gl.clearColor(1.0, 0.0, 0.0, 1.0) // Call cache median fill graph gl.clear(gl.COLOR_BUFFER_BIT) </script>
</body>
2.2 Drawing graphics using shaders

WebGL The coordinate system in


Introduction to shaders
The shader is Use OpenGL ES Shading Language A program written in a language , Responsible for recording pixels Location and Color , And by the Vertex shaders and clip shaders form , By using GLSL Write these shaders , And pass the code text to WebGL Compile at execution time , in addition , A collection of vertex shaders and fragment shaders, which we usually call Shader program .
Vertex shader The function of is to convert the input vertex from the original coordinate system to WebGL Scale space coordinate system used , The coordinate range of each axis is from -1.0 To 1.0, After the vertex shader makes the necessary transformations to the vertex coordinates , Save in the name gl_Position Standby in special variables .
Fragment Shader After the vertex shader processes the vertices of the shape , It will be called once by each pixel of each graph to be drawn , Its function is to determine the color value of pixels , And save it under the name gl_FragColor Of the special variables , The color value will eventually be drawn to the corresponding position of the graphics pixel .
Code
<body>
<canvas id="cvs" width="200" height="200" style="border: dashed 1px red">
Your browser does not support canvas elements
</canvas>
<script type="text/javascript"> // Get canvas elements var cvs = document.getElementById('cvs') // Get the context object of the element var gl = cvs.getContext('webgl') // Vertex shader variables var VSHADER_SOURCE = 'void main() {' + // Define the coordinates of the point and convert them into variables to save 'gl_Position = vec4(0.0, 0.0, 0.0, 1.0); ' + // Sets the diameter of the zoom distance 'gl_PointSize = 10.0; ' + '} ' // Clip shader variables var FSHADER_SOURCE = 'void main() {' + // Set the color of graphics pixels and save 'gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);' + '}' // Create a new shader object for loading vertex strings var vertShader = gl.createShader(gl.VERTEX_SHADER) // Load the saved vertex code string variable gl.shaderSource(vertShader, VSHADER_SOURCE) // Compile vertex shader gl.compileShader(vertShader) // Create a new shader object for loading fragment strings var fragShader = gl.createShader(gl.FRAGMENT_SHADER) // Load the saved fragment code string variable gl.shaderSource(fragShader, FSHADER_SOURCE) // Compiling fragment shaders gl.compileShader(fragShader) // Create a new program var shaderProgram = gl.createProgram() // Attach two compiled shader objects respectively gl.attachShader(shaderProgram, vertShader) gl.attachShader(shaderProgram, fragShader) // Link two attached shader programs gl.linkProgram(shaderProgram) // Use of open program gl.useProgram(shaderProgram) // Draw a drawing at a specified location gl.drawArrays(gl.POINTS, 0, 1) </script>
</body>
The first 3 Chapter - Draw triangle
3.1 Method of multipoint rendering

- what attribute Variable
It is a storage qualifier , To define a attribute Global variable of , The data of this variable will be transferred from the outside to the vertex shader , And save The vertices Relevant data , Only vertex shaders can use it .
- Use attribute Variable
- In the vertex shader , Make a statement attribute Variable .
- take attribute A variable is assigned to gl_Position Variable .
- towards attribute Variables transfer data .
- Use cache Association attribute Variable
- Create cache object
- Bind cache object
- Write data to object
- Assign cache objects to attribute Variable
- Turn on attribute Variable
3.2 Drawing triangle method
<body>
<canvas id="cvs" width="200" height="200" style="border: dashed 1px red">
Your browser does not support canvas elements
</canvas>
<script type="text/javascript"> // Get canvas elements var cvs = document.getElementById('cvs') // Get the context object of the element var gl = cvs.getContext('webgl') // Vertex shader variables var VSHADER_SOURCE = // Use the storage qualifier to define a variable that accepts vertex coordinates 'attribute vec4 a_Position;' + 'void main() {' + // Define the coordinates of the point and convert them into variables to save 'gl_Position = a_Position; ' + '} ' // Clip shader variables var FSHADER_SOURCE = 'void main() {' + // Set the color of graphics pixels and save 'gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);' + '}' // Create a new shader object for loading vertex strings var vertShader = gl.createShader(gl.VERTEX_SHADER) // Load the saved vertex code string variable gl.shaderSource(vertShader, VSHADER_SOURCE) // Compile vertex shader gl.compileShader(vertShader) // Create a new shader object for loading fragment strings var fragShader = gl.createShader(gl.FRAGMENT_SHADER) // Load the saved fragment code string variable gl.shaderSource(fragShader, FSHADER_SOURCE) // Compiling fragment shaders gl.compileShader(fragShader) // Create a new program var shaderProgram = gl.createProgram() // Attach two compiled shader objects respectively gl.attachShader(shaderProgram, vertShader) gl.attachShader(shaderProgram, fragShader) // Link two attached shader programs gl.linkProgram(shaderProgram) // Use of open program gl.useProgram(shaderProgram) // Define a type array to hold vertex coordinate values var vertices = new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]) // First create a cache object var vertexBuffer = gl.createBuffer() // Describe the type of cache object saved gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer) // Write coordinate data gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW) // Gets the variable in the vertex shader var a_Position = gl.getAttribLocation(shaderProgram, 'a_Position') // Assign coordinate values to variables gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0) // Enable the use of variable values gl.enableVertexAttribArray(a_Position) // Draw a drawing at a specified location gl.drawArrays(gl.TRIANGLES, 0, 3) </script>
</body>
The first 4 Chapter -WebGL Animation
4.1 Graphics move

- The translation principle
To translate a triangle , Just move each vertex of it , That is, add a component to each vertex , Get a new coordinate :
X1=X+TX``Y1=Y+TY``Z1=Z+TZ
You only need to add a constant to each component of vertex coordinates in the shader , Of course, this modification is on the vertex shader .
- uniform Type variable
Used to save and transmit consistent data , It can be used for both vertices , It can also be used for fragments .
<body>
<canvas id="cvs" width="200" height="200" style="border: dashed 1px red">
Your browser does not support canvas elements
</canvas>
<script type="text/javascript"> // Get canvas elements var cvs = document.getElementById('cvs') // Get the context object of the element var gl = cvs.getContext('webgl') // Vertex shader variables var VSHADER_SOURCE = // Use the storage qualifier to define a variable that accepts vertex coordinates 'attribute vec4 a_Position;' + // Use the storage qualifier to define a variable that accepts a consistent offset 'uniform vec4 u_Translation;' + 'void main() {' + // Define the coordinates of the point and convert them into variables to save 'gl_Position = a_Position + u_Translation; ' + '} ' // Clip shader variables var FSHADER_SOURCE = 'void main() {' + // Set the color of graphics pixels and save 'gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);' + '}' // Create a new shader object for loading vertex strings var vertShader = gl.createShader(gl.VERTEX_SHADER) // Load the saved vertex code string variable gl.shaderSource(vertShader, VSHADER_SOURCE) // Compile vertex shader gl.compileShader(vertShader) // Create a new shader object for loading fragment strings var fragShader = gl.createShader(gl.FRAGMENT_SHADER) // Load the saved fragment code string variable gl.shaderSource(fragShader, FSHADER_SOURCE) // Compiling fragment shaders gl.compileShader(fragShader) // Create a new program var shaderProgram = gl.createProgram() // Attach two compiled shader objects respectively gl.attachShader(shaderProgram, vertShader) gl.attachShader(shaderProgram, fragShader) // Link two attached shader programs gl.linkProgram(shaderProgram) // Use of open program gl.useProgram(shaderProgram) // Define a type array to hold vertex coordinate values var vertices = new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]) // First create a cache object var vertexBuffer = gl.createBuffer() // Describe the type of cache object saved gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer) // Write coordinate data gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW) // Gets the variable in the vertex shader var a_Position = gl.getAttribLocation(shaderProgram, 'a_Position') // Assign coordinate values to variables gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0) // Enable the use of variable values gl.enableVertexAttribArray(a_Position) // Define the uniform offset of each coordinate point var Tx = 0.2, Ty = 0.3, Tz = 0.0 // Get into vertex shader uniform Variable var u_Translation = gl.getUniformLocation(shaderProgram, 'u_Translation') // Assign multiple offset values to uniform Variable gl.uniform4f(u_Translation, Tx, Ty, Tz, 0.0) // Draw a drawing at a specified location gl.drawArrays(gl.TRIANGLES, 0, 3) </script>
</body>
4.2 Graphics rotation

Rotation principle
In order to describe the rotation process of a figure , The following must be specified :
- Rotation axis ( around X and Y Shaft rotation )
- Direction of rotation ( Clockwise and counterclockwise ), Negative values are clockwise , Counterclockwise when positive
- The angle of rotation ( Angle through which the figure passes )


4.3 Graphics zoom

-
The principle of scaling
By changing the matrix value in the original graph , Realize the effect of drawing enlargement and contraction , therefore , Just modify the matrix value of the original graph .

-
Animation to achieve
demand : Make an animation of rotating triangles by
effect :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-MmKI0duN-1649683016895)(/Users/taoguorong/Documents/Snagit/ Page high performance graphics programming /01 note /img/2019-03-29_15-13-39_01.jpg)]](/img/11/208371dbc9bb1175f199ed21d4f651.png)
Screen refresh rate
The speed at which images are updated on the screen , That is, the number of times the image on the screen appears per second , It's usually 60Hz The screen of every 16.7ms Refresh once .
Animation principle
When the image is refreshed , Elicit in a coherent manner 、 Make transition changes in a smooth way .
The core approach
requestAnimationFrame(callback)
// Execute an animation , And call before next rendering. callback The callback function updates the animation
The first 5 Chapter -WebGL Color
5.1 Introduction to operation steps

- Color adding steps
- Define an attribute variable in the vertex shader that receives externally passed in color values a_Color And a variable for transferring the obtained color value v_Color
- Define a of the same type and name in the clip shader v_Color Variable receives the value passed in from the vertex .
- Retyped array of vertex coordinates and color values
- Pass the array value into the cache and take it out , Two variables assigned to vertices
- Receive cached values and draw graphics and colors
-
vertexAttribPointer Method
-
Parameters explain The first 1 Parameters Specify to be assigned attribute Where variables are stored The first 2 Parameters Specifies the number of components per vertex in the cache (1~4) The first 3 Parameters Type a , Unsigned bytes , Short integer , Signed short integer , integer , Unsigned integer , floating-point The first 4 Parameters Indicates whether to classify non floating point data into [0,1][-1,1] Section The first 5 Parameters Bytes of two adjacent vertices . The default is 0 The first 6 Parameters Represents the offset of the cache object ( In bytes ),attribute Where do variables start to be stored in the buffer -
Case realization
- Add canvas elements , And get the webGL object , Save in variable .
- Define shader content , And compile the attachment .
- Use cache objects to transfer multiple coordinate data to vertices .
- Draw the image according to the coordinate data .
5.2 Shader compilation and image rendering
<body>
<canvas id="cvs" width="200" height="200" style="border: dashed 1px red">
Your browser does not support canvas elements
</canvas>
<script type="text/javascript"> // Get canvas elements var cvs = document.getElementById('cvs') // Get the context object of the element var gl = cvs.getContext('webgl') // Vertex shader variables var VSHADER_SOURCE = // Use the storage qualifier to define a variable that accepts vertex coordinates 'attribute vec4 a_Position;' + 'attribute vec4 a_Color;' + 'varying vec4 v_Color;' + 'void main() {' + // Define the coordinates of the point and convert them into variables to save 'gl_Position = a_Position; ' + 'v_Color = a_Color; ' + '} ' // Clip shader variables var FSHADER_SOURCE = 'precision mediump float;' + 'varying vec4 v_Color;' + 'void main() {' + // Set the color of graphics pixels and save 'gl_FragColor = v_Color ;' + '}' // Create a new shader object for loading vertex strings var vertShader = gl.createShader(gl.VERTEX_SHADER) // Load the saved vertex code string variable gl.shaderSource(vertShader, VSHADER_SOURCE) // Compile vertex shader gl.compileShader(vertShader) // Create a new shader object for loading fragment strings var fragShader = gl.createShader(gl.FRAGMENT_SHADER) // Load the saved fragment code string variable gl.shaderSource(fragShader, FSHADER_SOURCE) // Compiling fragment shaders gl.compileShader(fragShader) // Create a new program var shaderProgram = gl.createProgram() // Attach two compiled shader objects respectively gl.attachShader(shaderProgram, vertShader) gl.attachShader(shaderProgram, fragShader) // Link two attached shader programs gl.linkProgram(shaderProgram) // Use of open program gl.useProgram(shaderProgram) // Define a type array to hold vertex coordinate values var vertices = new Float32Array([ // x, y, red, green, blue 0.0, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, ]) // First create a cache object var vertexBuffer = gl.createBuffer() // Describe the type of cache object saved gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer) // Write coordinate data gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW) // Gets the number of bytes of a single element in the array var FSIZE = vertices.BYTES_PER_ELEMENT // Gets the variable in the vertex shader var a_Position = gl.getAttribLocation(shaderProgram, 'a_Position') // Assign coordinate values to variables gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 5, 0) // Enable the use of variable values gl.enableVertexAttribArray(a_Position) // Gets the variable in the vertex shader var a_Color = gl.getAttribLocation(shaderProgram, 'a_Color') // Assign coordinate values to variables gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 5, FSIZE * 2) // Enable the use of variable values gl.enableVertexAttribArray(a_Color) // Draw a drawing at a specified location gl.drawArrays(gl.TRIANGLES, 0, 3) </script>
</body>
版权声明
本文为[Xiao Shen Yue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212156117764.html
边栏推荐
- 联想公布ESG新进展:承诺2025年全线计算机产品100%含有再生塑料
- Push to origin / Master was rejected: error reporting solution
- Ffmpeg serial 2 - separate video and audio
- TCP / IP protocol
- Push to origin/master was rejected:报错解决办法
- LU decomposition, LDLT decomposition and Cholesky decomposition_ Zjuzly's blog - CSDN blog_ ldlt
- 【ES6】数组的扩展
- Architecture document of outsourcing student management system
- Authing officially joined the W3C organization and will participate in the formulation of relevant international standards
- [music suitable for programming]
猜你喜欢

EventBridge 集成云服务实践

Online yaml to properties tool

ROS robot from starting point to end point (IV) reproduction of blue bridge cloud practice

Outsourcing student management system architecture design document

软件测试分类与软件测试的原则

Hard core strength, recognized by many parties | cloud expansion technology, as the core manufacturer of RPA, was selected into the 2022 China RPA procurement guide

Free your hands and recommend a low code tool open source by Alibaba, yyds~

Helm installation sonarqube (bitnami) 9.3

iphone测试,自定义tabbar的图片会跟着屏幕滑动

搭建本地Canal中间件进行数据迁移 —— 从缓存击穿得到的启发
随机推荐
Serviceworker cache and HTTP cache
Outsourcing student management system architecture design document
MySQL is the most complete arrangement (interview questions + Notes + Guide Map), and the big interview companies are no longer stumped by mysql
联想公布ESG新进展:承诺2025年全线计算机产品100%含有再生塑料
Hard core strength, recognized by many parties | cloud expansion technology, as the core manufacturer of RPA, was selected into the 2022 China RPA procurement guide
JS to realize automatic scrolling of announcements
分析师认为三星Galaxy Z Fold 4和Z Flip 4可能比其前代产品更便宜
Online CSV to yaml tool
[use case level definition]
一加连发两款耳机产品:充电10分钟 听歌20小时
Restcloud ETL out of the box - permanently free
EventBridge 集成云服务实践
在线YAML转Properties工具
Use try-with-resources or close this “FileOutputStream“
【ES6】变量的解构赋值
Jupyter notebook has no run button
软件测试流程与测试模型
Download and install the vscade plug-in package offline
Live555 learning
How to set the South parameter when streaming from libvlc library