www.xbdev.net
xbdev - software development
Friday February 6, 2026
Home | Contact | Support | WebGPU Graphics and Compute ... | LearnWebGPU Series Step by step guide with interactive examples.....
     
 

LearnWebGPU
Series

Lights and Rays ...

 



[TOC] Chapter 5: Rendering Basics


Introduction


This chapter explores the essentials of rendering in WebGPU, starting with setting up WebGPU, understanding shader programs, and examining the step-by-step rendering process. We'll also consider factors affecting rendering speed, which is crucial for high-performance applications.

Pre-processing: WebGPU Setup


To start using WebGPU, it’s necessary to set up the rendering environment. This involves getting access to the WebGPU device and context, creating a `Canvas` element for displaying the rendered output, and configuring a `SwapChain` to handle frame rendering.

Here's a basic setup:

async function setupWebGPU(canvas) {
    if (!
navigator.gpu) {
        throw new 
Error("WebGPU not supported on this browser.");
    }

    
// Request the WebGPU adapter and device
    
const adapter await navigator.gpu.requestAdapter();
    const 
device await adapter.requestDevice();

    
// Configure the rendering context for the canvas
    
const context canvas.getContext("webgpu");
    const 
format "bgra8unorm";  // Preferred format for color rendering
    
context.configure({
        
device,
        
format,
    });

    return { 
devicecontextformat };
}

// Usage
const canvas document.getElementById("webgpu-canvas");
setupWebGPU(canvas).then(({ devicecontext }) => {
    
console.log("WebGPU setup complete.");
});


A Brief Introduction to Shader Programs


Shaders are small programs that run on the GPU to control how graphics are rendered. WebGPU primarily uses two types of shaders: vertex shaders, which process each vertex in a model, and fragment shaders, which handle the coloring of each pixel.

WebGPU shaders are typically written in WGSL (WebGPU Shading Language). Here’s an example of a simple vertex shader in WGSL:

@vertex
fn main( @location(0positionvec3<f32>) -> @builtin(positionvec4<f32> {
    return 
vec4<f32>(position1.0);
}


This vertex shader takes a 3D position as input and outputs a `vec4` position compatible with WebGPU’s rendering pipeline.

Rendering Steps


Rendering in WebGPU consists of multiple stages: setting up the pipeline, configuring buffers, and executing draw commands within a render pass. These steps are part of every WebGPU rendering function and ensure that models and scenes are properly rendered on the canvas.

1. Initialize Buffers: Store vertex data, indices, and other model information.
2. Create the Render Pipeline: Set up the shaders and specify how vertices and fragments are processed.
3. Render Pass Execution: Send commands to the GPU, including draw commands, which finalize each frame.

Rendering Speed Considerations


Rendering speed can be impacted by factors like model complexity, shader efficiency, and buffer handling. Simplifying models, using optimized shaders, and managing memory efficiently can all help maintain fast frame rates in WebGPU applications.




A Primer on Shaders


A fragment represents a pixel in the context of GPU rendering. Fragment shaders determine each fragment’s color, opacity, and other properties. Fragments can vary based on lighting, materials, or textures applied to the model, allowing for detailed and visually rich scenes.

Shaders use a specific set of variables, such as `uniforms` (for global settings), `varyings` (to pass data between shaders), and inputs and outputs for position, color, and texture coordinates. These variables ensure data is transmitted correctly between the vertex and fragment stages.

The Simplest Shaders Possible


Here’s an example of a minimal vertex and fragment shader pair in WGSL:

Vertex Shader (WGSL):
@vertex
fn vs_main( @location(0positionvec3<f32>) -> @builtin(positionvec4<f32> {
    return 
vec4<f32>(position1.0);
}


Fragment Shader (WGSL):
@fragment
fn fs_main() -> @location(0vec4<f32> {
    return 
vec4<f32>(0.00.80.21.0);  // Outputs green color
}


These shaders take a vertex position and output a solid green color.




A Primer on Buffer Objects


Creating and Initializing Buffer Objects


Buffer objects store vertex, index, and other data that shaders use during rendering. WebGPU buffers are created by specifying their size, usage (e.g., as vertex or index buffers), and optionally, initial data.

Example of a simple vertex buffer creation:

const vertexData = new Float32Array([
    -
1.0, -1.00.0,  // Vertex 1
     
1.0, -1.00.0,  // Vertex 2
     
0.0,  1.00.0,  // Vertex 3
]);

const 
vertexBuffer device.createBuffer({
    
sizevertexData.byteLength,
    
usageGPUBufferUsage.VERTEX GPUBufferUsage.COPY_DST,
    
mappedAtCreationtrue
});
new 
Float32Array(vertexBuffer.getMappedRange()).set(vertexData);
vertexBuffer.unmap();


Shaders, Buffers, and the Graphics Pipeline


Buffers connect to shaders through the graphics pipeline. The pipeline specifies how data flows through vertex and fragment shaders, defining the stages of rendering from input to output.




Simple Model


A Simple 3D Model


To render a 3D model, WebGPU needs a set of vertices and potentially indices. A simple model like a triangle can be defined by three vertices, as in the `vertexData` array above.

A Side Note about JavaScript Functions


JavaScript functions for WebGPU are asynchronous, handling GPU tasks that take time to process. Using `async` and `await` enables smooth execution of these tasks.




Example 1: One Color per Model


To render a model in a single color, the fragment shader outputs a fixed color. This approach is efficient and simple.

@fragment
fn fs_main() -> @location(0vec4<f32> {
    return 
vec4<f32>(1.00.00.01.0);  // Outputs red color
}


Example 2: One Color per Triangle


To render each triangle with a unique color, we can use an array of colors and pass an index per triangle.

Example 3: One Color per Vertex


Vertex colors require each vertex to store a color attribute, which the fragment shader interpolates.

Example 4: Textures


Applying textures involves loading image data into a texture object and sampling it in the fragment shader. WebGPU handles textures as 2D arrays that can be accessed by the shaders.




Interleaved Buffers


Managing Buffer Objects


Interleaving buffers means storing multiple attributes (position, color, normal) within the same buffer. This reduces buffer switching overhead and can improve performance.

const interleavedData = new Float32Array([
    
// Vertex Position  // Color
    
-1.0, -1.00.0,   1.00.00.0,  // Vertex 1: red
     
1.0, -1.00.0,   0.01.00.0,  // Vertex 2: green
     
0.0,  1.00.0,   0.00.01.0,  // Vertex 3: blue
]);


Converting JSON Model Data to Buffer Objects


This topic was discussed in the previous chapter, where JSON data from Blender or other tools can be parsed and converted into WebGPU buffers.

Summary


In this chapter, we explored WebGPU rendering basics, covering setup, shaders, buffers, and simple model rendering examples. By understanding these core concepts, you can begin creating efficient and visually engaging WebGPU applications.







101 WebGPU Programming Projects. WebGPU Development Pixels - coding fragment shaders from post processing to ray tracing! WebGPU by Example: Fractals, Image Effects, Ray-Tracing, Procedural Geometry, 2D/3D, Particles, Simulations WebGPU Games WGSL 2d 3d interactive web-based fun learning WebGPU Compute WebGPU API - Owners WebGPU Development Cookbook - coding recipes for all your webgpu needs! WebGPU & WGSL Essentials: A Hands-On Approach to Interactive Graphics, Games, 2D Interfaces, 3D Meshes, Animation, Security and Production Kenwright graphics and animations using the webgpu api 12 week course kenwright learn webgpu api kenwright programming compute and graphics applications with html5 and webgpu api kenwright real-time 3d graphics with webgpu kenwright webgpu for dummies kenwright webgpu wgsl compute graphics all in one kenwright webgpu api develompent a quick start guide kenwright webgpu by example 2022 kenwright webgpu gems kenwright webgpu interactive compute and graphics visualization cookbook kenwright wgsl webgpu shading language cookbook kenwright WebGPU Shader Language Development: Vertex, Fragment, Compute Shaders for Programmers Kenwright WGSL Fundamentals book kenwright WebGPU Data Visualization Cookbook kenwright Special Effects Programming with WebGPU kenwright WebGPU Programming Guide: Interactive Graphics and Compute Programming with WebGPU & WGSL kenwright Ray-Tracing with WebGPU kenwright



 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.