惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

WebGL Fundamentals

WebGL Using 2 or More Textures WebGL Implementing DrawImage WebGL 2D Matrices WebGL Implementing A Matrix Stack WebGL 2D Rotation WebGL 2D Scale WebGL 2D Translation WebGL - Rasterization vs 3D libraries WebGL 3D - Cameras WebGL 3D Geometry - Lathe WebGL 3D - Directional Lighting WebGL 3D - Point Lighting WebGL 3D - Normal Mapping WebGL 3D - Spot Lighting WebGL - Orthographic 3D WebGL 3D Perspective Correct Texture Mapping WebGL 3D Perspective WebGL Textures WebGL and Alpha WebGL - Animation WebGL Anti-Patterns WebGL Attributes WebGL Boilerplate WebGL - Cross Origin Images WebGL Cross Platform Issues WebGL Cubemaps WebGL 3D - Data Textures WebGL - Drawing Multiple Things WebGL Drawing Without Data WebGL Environment Maps (reflections) WebGL Fog WebGL Framebuffers WebGL Fundamentals WebGL GPGPU WebGL How It Works WebGL Image Processing Continued WebGL Image Processing WebGL Indexed Vertices WebGL Optimization - Instanced Drawing WebGL - Less Code, More Fun WebGL Load Obj with Mtl WebGL Load Obj WebGL Matrices vs Math Matrices WebGL Multiple Views, Multiple Canvases WebGL Picking WebGL Planar and Perspective Projection Mapping WebGL Points, Lines, and Triangles WebGL Post Processing WebGL Precision Issues WebGL Pulling Vertices Accessing textures by pixel coordinate in WebGL2 A simple way to show the load on the GPU's vertex and fragment processing? Apply a displacement map and specular map Can anyone explain what this GLSL fragment shader is doing? Can I mute the warning about vertex attrib 0 being disabled? Create image warping effect in WebGL Creating a smudge/liquify effect How to draw Depth Sprites Determine min/max values for the entire image Don't blend a polygon that crosses itself Drawing 2D image with depth map to achieve pseudo-3D effect Drawing a heightmap Drawing layers with different points Drawing Many different models in a single draw call Drawing textured sprites with instanced drawing Efficient particle system in javascript? (WebGL) Emulating palette based graphics in WebGL FPS-like camera movement with basic matrix transformations Get the size of a point for collision checking GLSL shader to support coloring and texturing How can I compute for 500 points which of 1000 line segments is nearest to each point? How can I create a 16bit historgram of 16bit data How can I get all the uniforms and uniformBlocks How can I move the perspective vanishing point from the center of the canvas? How to Achieve Moving Line with Trail Effects How to bind an array of textures to a WebGL shader uniform? How to blend colors across 2 triangles How to combine more text drawing into fewer draw calls How to control the color between vertices How to create a torus How to detect clipped triangles in the framgment shader How to determine the average brightness in a scene? How to draw correctly textured trapezoid polygons How to fade the drawing buffer How to figure out how much GPU work to do without crashing WebGL How to get audio data into a shader How to get code completion for WebGL in Visual Studio Code How to get the 3d coordinates of a mouse click How to get pixelize effect in webgl? How to implement zoom from mouse in 2D WebGL How to import a heightmap in WebGL How to load images in the background with no jank How to make a smudge brush tool How to make WebGL canvas transparent How to prevent texture bleeding with a texture atlas How to process particle positions How to read a single component with readPixels How to render large scale images like 32000x32000 How to simulate a 3D texture in WebGL How to support both WebGL and WebGL2
How to optimize rendering a UI
WebGLFundame · 2025-02-26 · via WebGL Fundamentals

Question:

I'm just getting started with webgl. I followed a simple beginners tutorial on youtube. Now, I'm trying to create a simple 2D game.

In that game, I want to render a simple inventory with images. When I do this, my fps drops down to 2 after 10 seconds. If I remove the code for the inventory rendering, it stays at 60.

I know that my problem is on line 82 in game/js/engine/inventory/inventory.js. There, I render 35 images with a sprite class that I made watching the tutorial. I think because I watched a simple tutorial in which the code that is rendering the image isn't optimized and probably isn't the best way to do it. The sprite class is located in game/js/engine/material.js:127. In the sprite class, I setup simple variables that can be parsed to my vertex and fragment shader.

Sprite setup

In the setup method I setup all the parameters for my image.

gl.useProgram(this.material.program);

this.gl_tex = gl.createTexture();

gl.bindTexture(gl.TEXTURE_2D, this.gl_tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.image);
gl.bindTexture(gl.TEXTURE_2D, null);

this.uv_x = this.size.x / this.image.width;
this.uv_y = this.size.y / this.image.height;

this.tex_buff = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex_buff);
gl.bufferData(gl.ARRAY_BUFFER, Sprite.createRenderRectArray(0, 0, this.uv_x, this.uv_y), gl.STATIC_DRAW);

this.geo_buff = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.geo_buff);
gl.bufferData(gl.ARRAY_BUFFER, Sprite.createRectArray(0, 0, this.size.x, this.size.y), gl.STATIC_DRAW);

gl.useProgram(null);

Sprite render

In the render method, I first bind the texture. Then, I bind a tex coord buffer, a geo buffer and some offsets for my world. Finally, I draw arrays.

let frame_x = Math.floor(frames.x) * this.uv_x;
let frame_y = Math.floor(frames.y) * this.uv_y;

let oMat = new M3x3().transition(position.x, position.y);
gl.useProgram(this.material.program);

this.material.set("u_color", 1, 1, 1, 1);

gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.gl_tex);
this.material.set("u_image", 0);

gl.bindBuffer(gl.ARRAY_BUFFER, this.tex_buff);
this.material.set("a_texCoord");

gl.bindBuffer(gl.ARRAY_BUFFER, this.geo_buff);
this.material.set("a_position");

this.material.set("u_texeloffset", 0.5 / (this.image.width * scale.x), 0.5 / (this.image.height * scale.y));
this.material.set("u_frame", frame_x, frame_y);
this.material.set("u_world", worldSpaceMatrix.getFloatArray());
this.material.set("u_object", oMat.getFloatArray());

gl.drawArrays(gl.TRIANGLE_STRIP, 0, 6);
gl.useProgram(null);

Github: https://github.com/DJ1TJOO/2DGame/

Does someone have an idea on how I can fixe/optimize it? Or maybe there is a better way to render an inventory?

If you find any other way to improve my webgl or javascript, please tell me.

Answer:

is a better way to render an inventory?

There are a few ways to optimize off the top of my head.

  1. It might be faster to just use HTML for your inventory

    Seriously: You also gain easy international font rendering, styling, responsiveness with CSS, etc... Plenty of games do this.

  2. It's generally faster to use a texture atlas (a single texture with lots of different images), then generate vertices into a vertex buffer for all the parts of your inventory. Then draw all of it with a single draw call. This is how for example Dear ImGUI works to make all of these amazing GUIs. It doesn't draw anything itself, it just generates a vertex buffer with positions and texture coordinates for a texture atlas.

  3. Do #2 except instead of generating the entire vertex buffer every frame just update the parts that change.

    So for example let's say your inventory says

     [gold  ] 123
     [silver] 54
     [copper] 2394
    

    Let's assume you always draw [gold ], [silver] and [copper] but only the numbers change. You could generate vertex buffers that contain all the positions for each letter as a sprite and then say 6 character place holders for each value. You only have to update the numbers when they change by remembering where they are in the vertex buffers. For any digit you don't want to draw you can just move its vertices offscreen.

  4. Draw the inventory in to a texture (or parts of it). Then draw the texture on the screen. Only update the parts of the texture that change.

    This is basically what the browser itself does. Based on various CSS settings the parts of the page are divided into textures. When some HTML or CSS changes only those textures in which something changed are re-rendered and then all the textures are drawn to re-composite the page.

The question and quoted portions thereof are CC BY-SA 4.0 by DJ1TJOO from here