Skip to content

15.4 新兴Web技术

关键词: WebXR, WebGL, HTTP/3, 边缘计算, WebGPU, WebCodecs, 新兴技术, 未来趋势

学习目标

  • 了解WebXR虚拟现实技术的基本概念和应用
  • 掌握WebGL 3D图形渲染的基础知识
  • 理解HTTP/3协议的新特性和优势
  • 学习边缘计算在Web开发中的应用
  • 探索其他新兴Web技术的发展趋势

15.4.1 WebXR虚拟现实技术

WebXR基础概念

WebXR是一个用于在Web上创建虚拟现实(VR)和增强现实(AR)体验的API集合。

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebXR示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #1a1a1a;
            color: white;
        }
        
        .xr-container {
            text-align: center;
            padding: 20px;
        }
        
        .xr-button {
            background-color: #0066cc;
            color: white;
            border: none;
            padding: 15px 30px;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
            margin: 10px;
        }
        
        .xr-button:hover {
            background-color: #0052a3;
        }
        
        .xr-button:disabled {
            background-color: #666;
            cursor: not-allowed;
        }
        
        .status {
            margin: 20px 0;
            padding: 10px;
            background-color: #333;
            border-radius: 5px;
        }
        
        #canvas {
            background-color: #000;
            border: 2px solid #333;
        }
    </style>
</head>
<body>
    <div class="xr-container">
        <h1>WebXR虚拟现实示例</h1>
        
        <div class="status" id="status">
            检查WebXR支持...
        </div>
        
        <canvas id="canvas" width="800" height="600"></canvas>
        
        <div>
            <button class="xr-button" id="vrButton" disabled>进入VR模式</button>
            <button class="xr-button" id="arButton" disabled>进入AR模式</button>
        </div>
    </div>

    <script>
        // WebXR示例代码
        let xrSession = null;
        let xrRefSpace = null;
        let gl = null;
        let canvas = null;
        
        // 初始化WebXR
        async function initWebXR() {
            const statusDiv = document.getElementById('status');
            canvas = document.getElementById('canvas');
            
            // 检查WebXR支持
            if (!navigator.xr) {
                statusDiv.textContent = '❌ 浏览器不支持WebXR';
                return;
            }
            
            try {
                // 检查VR支持
                const vrSupported = await navigator.xr.isSessionSupported('immersive-vr');
                const arSupported = await navigator.xr.isSessionSupported('immersive-ar');
                
                statusDiv.innerHTML = `
                    ✅ WebXR支持已启用<br>
                    VR支持: ${vrSupported ? '是' : '否'}<br>
                    AR支持: ${arSupported ? '是' : '否'}
                `;
                
                // 启用按钮
                document.getElementById('vrButton').disabled = !vrSupported;
                document.getElementById('arButton').disabled = !arSupported;
                
                // 初始化WebGL
                initWebGL();
                
            } catch (error) {
                statusDiv.textContent = '❌ WebXR初始化失败: ' + error.message;
            }
        }
        
        // 初始化WebGL
        function initWebGL() {
            gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
            if (!gl) {
                document.getElementById('status').textContent = '❌ WebGL不支持';
                return;
            }
            
            // 设置WebGL视口
            gl.viewport(0, 0, canvas.width, canvas.height);
            gl.clearColor(0.0, 0.0, 0.2, 1.0);
            
            // 开始渲染循环
            render();
        }
        
        // 渲染循环
        function render() {
            if (xrSession) {
                // XR渲染
                xrSession.requestAnimationFrame(onXRFrame);
            } else {
                // 普通渲染
                gl.clear(gl.COLOR_BUFFER_BIT);
                
                // 绘制简单的彩色方块
                drawColoredQuad();
                
                requestAnimationFrame(render);
            }
        }
        
        // 绘制彩色方块
        function drawColoredQuad() {
            // 简化的WebGL渲染代码
            const vertices = [
                -0.5, -0.5, 1.0, 0.0, 0.0, 1.0,
                 0.5, -0.5, 0.0, 1.0, 0.0, 1.0,
                 0.0,  0.5, 0.0, 0.0, 1.0, 1.0
            ];
            
            // 这里应该有完整的WebGL渲染管道
            // 为了简化,我们只是清空画布
            gl.clear(gl.COLOR_BUFFER_BIT);
        }
        
        // XR帧回调
        function onXRFrame(time, frame) {
            const session = frame.session;
            const pose = frame.getViewerPose(xrRefSpace);
            
            if (pose) {
                // 渲染XR帧
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
                
                for (const view of pose.views) {
                    // 为每个视图渲染
                    const viewport = session.renderState.baseLayer.getViewport(view);
                    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
                    
                    // 渲染3D内容
                    renderXRContent(view);
                }
            }
            
            session.requestAnimationFrame(onXRFrame);
        }
        
        // 渲染XR内容
        function renderXRContent(view) {
            // 这里应该有3D内容渲染
            // 使用view.transform和view.projectionMatrix进行渲染
            
            // 简化的示例:绘制一个虚拟立方体
            drawVirtualCube();
        }
        
        // 绘制虚拟立方体
        function drawVirtualCube() {
            // 简化的立方体渲染
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            
            // 这里应该有完整的3D立方体渲染代码
            // 包括顶点缓冲、着色器、变换矩阵等
        }
        
        // 开始VR会话
        async function startVRSession() {
            try {
                xrSession = await navigator.xr.requestSession('immersive-vr', {
                    requiredFeatures: ['local-floor']
                });
                
                // 创建WebGL层
                const layer = new XRWebGLLayer(xrSession, gl);
                xrSession.updateRenderState({ baseLayer: layer });
                
                // 获取参考空间
                xrRefSpace = await xrSession.requestReferenceSpace('local-floor');
                
                // 开始XR渲染
                xrSession.requestAnimationFrame(onXRFrame);
                
                // 处理会话结束
                xrSession.addEventListener('end', () => {
                    xrSession = null;
                    xrRefSpace = null;
                    document.getElementById('vrButton').textContent = '进入VR模式';
                    render(); // 恢复普通渲染
                });
                
                document.getElementById('vrButton').textContent = '退出VR模式';
                
            } catch (error) {
                console.error('VR会话启动失败:', error);
                document.getElementById('status').textContent = '❌ VR会话启动失败';
            }
        }
        
        // 开始AR会话
        async function startARSession() {
            try {
                xrSession = await navigator.xr.requestSession('immersive-ar', {
                    requiredFeatures: ['local-floor']
                });
                
                // AR会话配置与VR类似
                const layer = new XRWebGLLayer(xrSession, gl);
                xrSession.updateRenderState({ baseLayer: layer });
                
                xrRefSpace = await xrSession.requestReferenceSpace('local-floor');
                xrSession.requestAnimationFrame(onXRFrame);
                
                xrSession.addEventListener('end', () => {
                    xrSession = null;
                    xrRefSpace = null;
                    document.getElementById('arButton').textContent = '进入AR模式';
                    render();
                });
                
                document.getElementById('arButton').textContent = '退出AR模式';
                
            } catch (error) {
                console.error('AR会话启动失败:', error);
                document.getElementById('status').textContent = '❌ AR会话启动失败';
            }
        }
        
        // 事件监听
        document.getElementById('vrButton').addEventListener('click', () => {
            if (xrSession) {
                xrSession.end();
            } else {
                startVRSession();
            }
        });
        
        document.getElementById('arButton').addEventListener('click', () => {
            if (xrSession) {
                xrSession.end();
            } else {
                startARSession();
            }
        });
        
        // 初始化
        window.addEventListener('load', initWebXR);
    </script>
</body>
</html>

15.4.2 WebGL 3D图形渲染

WebGL基础应用

WebGL为Web带来了硬件加速的3D图形渲染能力。

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebGL 3D渲染示例</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }
        
        .webgl-container {
            text-align: center;
        }
        
        canvas {
            border: 2px solid #333;
            background-color: #000;
        }
        
        .controls {
            margin: 20px 0;
        }
        
        .control-group {
            margin: 10px;
            display: inline-block;
        }
        
        .control-group label {
            display: block;
            margin-bottom: 5px;
        }
        
        input[type="range"] {
            width: 150px;
        }
        
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        .info {
            background-color: #e7f3ff;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="webgl-container">
        <h1>WebGL 3D图形渲染示例</h1>
        
        <div class="info">
            <h3>WebGL特性展示</h3>
            <p>• 硬件加速的3D图形渲染</p>
            <p>• 实时动画和交互</p>
            <p>• 着色器程序支持</p>
            <p>• 纹理映射和光照效果</p>
        </div>
        
        <canvas id="webglCanvas" width="800" height="600"></canvas>
        
        <div class="controls">
            <div class="control-group">
                <label for="rotationX">X轴旋转:</label>
                <input type="range" id="rotationX" min="0" max="360" value="0">
                <span id="rotationXValue">0°</span>
            </div>
            
            <div class="control-group">
                <label for="rotationY">Y轴旋转:</label>
                <input type="range" id="rotationY" min="0" max="360" value="0">
                <span id="rotationYValue">0°</span>
            </div>
            
            <div class="control-group">
                <label for="rotationZ">Z轴旋转:</label>
                <input type="range" id="rotationZ" min="0" max="360" value="0">
                <span id="rotationZValue">0°</span>
            </div>
            
            <div class="control-group">
                <button onclick="resetRotation()">重置旋转</button>
                <button onclick="toggleAnimation()">开始/停止动画</button>
                <button onclick="changeColor()">改变颜色</button>
            </div>
        </div>
        
        <div id="webglInfo"></div>
    </div>

    <script>
        let gl;
        let shaderProgram;
        let vertexBuffer;
        let colorBuffer;
        let rotationX = 0;
        let rotationY = 0;
        let rotationZ = 0;
        let isAnimating = false;
        let currentColor = [1.0, 0.0, 0.0, 1.0]; // 红色
        
        // 顶点着色器源码
        const vertexShaderSource = `
            attribute vec3 aVertexPosition;
            attribute vec4 aVertexColor;
            
            uniform mat4 uModelViewMatrix;
            uniform mat4 uProjectionMatrix;
            
            varying vec4 vColor;
            
            void main() {
                gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);
                vColor = aVertexColor;
            }
        `;
        
        // 片段着色器源码
        const fragmentShaderSource = `
            precision mediump float;
            varying vec4 vColor;
            
            void main() {
                gl_FragColor = vColor;
            }
        `;
        
        // 初始化WebGL
        function initWebGL() {
            const canvas = document.getElementById('webglCanvas');
            gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            
            if (!gl) {
                alert('WebGL不支持!');
                return false;
            }
            
            // 设置视口
            gl.viewport(0, 0, canvas.width, canvas.height);
            gl.clearColor(0.0, 0.0, 0.0, 1.0);
            gl.enable(gl.DEPTH_TEST);
            
            // 初始化着色器程序
            shaderProgram = initShaderProgram();
            if (!shaderProgram) {
                return false;
            }
            
            // 初始化缓冲区
            initBuffers();
            
            // 绑定控件事件
            bindControls();
            
            // 开始渲染
            render();
            
            // 显示WebGL信息
            showWebGLInfo();
            
            return true;
        }
        
        // 创建着色器
        function createShader(gl, type, source) {
            const shader = gl.createShader(type);
            gl.shaderSource(shader, source);
            gl.compileShader(shader);
            
            if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
                console.error('着色器编译错误:', gl.getShaderInfoLog(shader));
                gl.deleteShader(shader);
                return null;
            }
            
            return shader;
        }
        
        // 初始化着色器程序
        function initShaderProgram() {
            const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
            const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
            
            if (!vertexShader || !fragmentShader) {
                return null;
            }
            
            const program = gl.createProgram();
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);
            gl.linkProgram(program);
            
            if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
                console.error('着色器程序链接错误:', gl.getProgramInfoLog(program));
                return null;
            }
            
            return program;
        }
        
        // 初始化缓冲区
        function initBuffers() {
            // 立方体顶点
            const vertices = [
                // 前面
                -0.5, -0.5,  0.5,
                 0.5, -0.5,  0.5,
                 0.5,  0.5,  0.5,
                -0.5,  0.5,  0.5,
                
                // 后面
                -0.5, -0.5, -0.5,
                -0.5,  0.5, -0.5,
                 0.5,  0.5, -0.5,
                 0.5, -0.5, -0.5,
                
                // 顶面
                -0.5,  0.5, -0.5,
                -0.5,  0.5,  0.5,
                 0.5,  0.5,  0.5,
                 0.5,  0.5, -0.5,
                
                // 底面
                -0.5, -0.5, -0.5,
                 0.5, -0.5, -0.5,
                 0.5, -0.5,  0.5,
                -0.5, -0.5,  0.5,
                
                // 右面
                 0.5, -0.5, -0.5,
                 0.5,  0.5, -0.5,
                 0.5,  0.5,  0.5,
                 0.5, -0.5,  0.5,
                
                // 左面
                -0.5, -0.5, -0.5,
                -0.5, -0.5,  0.5,
                -0.5,  0.5,  0.5,
                -0.5,  0.5, -0.5,
            ];
            
            // 创建顶点缓冲区
            vertexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
            
            // 立方体颜色(每个面不同颜色)
            const colors = [
                1.0, 0.0, 0.0, 1.0, // 前面 - 红色
                1.0, 0.0, 0.0, 1.0,
                1.0, 0.0, 0.0, 1.0,
                1.0, 0.0, 0.0, 1.0,
                
                0.0, 1.0, 0.0, 1.0, // 后面 - 绿色
                0.0, 1.0, 0.0, 1.0,
                0.0, 1.0, 0.0, 1.0,
                0.0, 1.0, 0.0, 1.0,
                
                0.0, 0.0, 1.0, 1.0, // 顶面 - 蓝色
                0.0, 0.0, 1.0, 1.0,
                0.0, 0.0, 1.0, 1.0,
                0.0, 0.0, 1.0, 1.0,
                
                1.0, 1.0, 0.0, 1.0, // 底面 - 黄色
                1.0, 1.0, 0.0, 1.0,
                1.0, 1.0, 0.0, 1.0,
                1.0, 1.0, 0.0, 1.0,
                
                1.0, 0.0, 1.0, 1.0, // 右面 - 品红
                1.0, 0.0, 1.0, 1.0,
                1.0, 0.0, 1.0, 1.0,
                1.0, 0.0, 1.0, 1.0,
                
                0.0, 1.0, 1.0, 1.0, // 左面 - 青色
                0.0, 1.0, 1.0, 1.0,
                0.0, 1.0, 1.0, 1.0,
                0.0, 1.0, 1.0, 1.0,
            ];
            
            // 创建颜色缓冲区
            colorBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
        }
        
        // 创建变换矩阵
        function createTransformMatrix() {
            const modelViewMatrix = mat4.create();
            
            // 移动到屏幕中心
            mat4.translate(modelViewMatrix, modelViewMatrix, [0.0, 0.0, -3.0]);
            
            // 应用旋转
            mat4.rotate(modelViewMatrix, modelViewMatrix, rotationX * Math.PI / 180, [1, 0, 0]);
            mat4.rotate(modelViewMatrix, modelViewMatrix, rotationY * Math.PI / 180, [0, 1, 0]);
            mat4.rotate(modelViewMatrix, modelViewMatrix, rotationZ * Math.PI / 180, [0, 0, 1]);
            
            return modelViewMatrix;
        }
        
        // 创建投影矩阵
        function createProjectionMatrix() {
            const canvas = document.getElementById('webglCanvas');
            const aspect = canvas.width / canvas.height;
            const projectionMatrix = mat4.create();
            
            mat4.perspective(projectionMatrix, Math.PI / 4, aspect, 0.1, 100.0);
            
            return projectionMatrix;
        }
        
        // 渲染场景
        function render() {
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            
            // 使用着色器程序
            gl.useProgram(shaderProgram);
            
            // 设置顶点属性
            const aVertexPosition = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
            gl.vertexAttribPointer(aVertexPosition, 3, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(aVertexPosition);
            
            // 设置颜色属性
            const aVertexColor = gl.getAttribLocation(shaderProgram, 'aVertexColor');
            gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
            gl.vertexAttribPointer(aVertexColor, 4, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(aVertexColor);
            
            // 设置矩阵uniform
            const uModelViewMatrix = gl.getUniformLocation(shaderProgram, 'uModelViewMatrix');
            const uProjectionMatrix = gl.getUniformLocation(shaderProgram, 'uProjectionMatrix');
            
            gl.uniformMatrix4fv(uModelViewMatrix, false, createTransformMatrix());
            gl.uniformMatrix4fv(uProjectionMatrix, false, createProjectionMatrix());
            
            // 绘制立方体
            const indices = [
                0, 1, 2, 0, 2, 3,    // 前面
                4, 5, 6, 4, 6, 7,    // 后面
                8, 9, 10, 8, 10, 11,  // 顶面
                12, 13, 14, 12, 14, 15, // 底面
                16, 17, 18, 16, 18, 19, // 右面
                20, 21, 22, 20, 22, 23  // 左面
            ];
            
            const indexBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
            
            gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
            
            // 动画循环
            if (isAnimating) {
                rotationY += 1;
                if (rotationY >= 360) rotationY = 0;
                updateControls();
                requestAnimationFrame(render);
            }
        }
        
        // 绑定控件事件
        function bindControls() {
            const rotationXSlider = document.getElementById('rotationX');
            const rotationYSlider = document.getElementById('rotationY');
            const rotationZSlider = document.getElementById('rotationZ');
            
            rotationXSlider.addEventListener('input', (e) => {
                rotationX = parseFloat(e.target.value);
                document.getElementById('rotationXValue').textContent = rotationX + '°';
                if (!isAnimating) render();
            });
            
            rotationYSlider.addEventListener('input', (e) => {
                rotationY = parseFloat(e.target.value);
                document.getElementById('rotationYValue').textContent = rotationY + '°';
                if (!isAnimating) render();
            });
            
            rotationZSlider.addEventListener('input', (e) => {
                rotationZ = parseFloat(e.target.value);
                document.getElementById('rotationZValue').textContent = rotationZ + '°';
                if (!isAnimating) render();
            });
        }
        
        // 更新控件显示
        function updateControls() {
            document.getElementById('rotationX').value = rotationX;
            document.getElementById('rotationY').value = rotationY;
            document.getElementById('rotationZ').value = rotationZ;
            document.getElementById('rotationXValue').textContent = rotationX + '°';
            document.getElementById('rotationYValue').textContent = rotationY + '°';
            document.getElementById('rotationZValue').textContent = rotationZ + '°';
        }
        
        // 重置旋转
        function resetRotation() {
            rotationX = 0;
            rotationY = 0;
            rotationZ = 0;
            updateControls();
            if (!isAnimating) render();
        }
        
        // 切换动画
        function toggleAnimation() {
            isAnimating = !isAnimating;
            if (isAnimating) {
                render();
            }
        }
        
        // 改变颜色
        function changeColor() {
            // 生成随机颜色
            const colors = [];
            for (let i = 0; i < 24; i++) {
                colors.push(Math.random(), Math.random(), Math.random(), 1.0);
            }
            
            // 更新颜色缓冲区
            gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
            
            if (!isAnimating) render();
        }
        
        // 显示WebGL信息
        function showWebGLInfo() {
            const info = `
                <h3>WebGL信息</h3>
                <p><strong>版本:</strong> ${gl.getParameter(gl.VERSION)}</p>
                <p><strong>着色器语言版本:</strong> ${gl.getParameter(gl.SHADING_LANGUAGE_VERSION)}</p>
                <p><strong>供应商:</strong> ${gl.getParameter(gl.VENDOR)}</p>
                <p><strong>渲染器:</strong> ${gl.getParameter(gl.RENDERER)}</p>
                <p><strong>最大纹理尺寸:</strong> ${gl.getParameter(gl.MAX_TEXTURE_SIZE)}</p>
                <p><strong>最大顶点属性:</strong> ${gl.getParameter(gl.MAX_VERTEX_ATTRIBS)}</p>
            `;
            document.getElementById('webglInfo').innerHTML = info;
        }
        
        // 矩阵工具函数(简化版)
        const mat4 = {
            create: function() {
                return new Float32Array([
                    1, 0, 0, 0,
                    0, 1, 0, 0,
                    0, 0, 1, 0,
                    0, 0, 0, 1
                ]);
            },
            
            perspective: function(out, fovy, aspect, near, far) {
                const f = 1.0 / Math.tan(fovy / 2);
                const nf = 1 / (near - far);
                
                out[0] = f / aspect;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                out[4] = 0;
                out[5] = f;
                out[6] = 0;
                out[7] = 0;
                out[8] = 0;
                out[9] = 0;
                out[10] = (far + near) * nf;
                out[11] = -1;
                out[12] = 0;
                out[13] = 0;
                out[14] = (2 * far * near) * nf;
                out[15] = 0;
            },
            
            translate: function(out, a, v) {
                out[12] = a[0] * v[0] + a[4] * v[1] + a[8] * v[2] + a[12];
                out[13] = a[1] * v[0] + a[5] * v[1] + a[9] * v[2] + a[13];
                out[14] = a[2] * v[0] + a[6] * v[1] + a[10] * v[2] + a[14];
                out[15] = a[3] * v[0] + a[7] * v[1] + a[11] * v[2] + a[15];
            },
            
            rotate: function(out, a, rad, axis) {
                const s = Math.sin(rad);
                const c = Math.cos(rad);
                const t = 1 - c;
                
                const x = axis[0];
                const y = axis[1];
                const z = axis[2];
                
                const tx = t * x;
                const ty = t * y;
                
                // 简化的旋转矩阵计算
                const b00 = tx * x + c;
                const b01 = tx * y + s * z;
                const b02 = tx * z - s * y;
                
                const b10 = tx * y - s * z;
                const b11 = ty * y + c;
                const b12 = ty * z + s * x;
                
                const b20 = tx * z + s * y;
                const b21 = ty * z - s * x;
                const b22 = t * z * z + c;
                
                const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
                const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
                const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
                
                out[0] = a00 * b00 + a10 * b01 + a20 * b02;
                out[1] = a01 * b00 + a11 * b01 + a21 * b02;
                out[2] = a02 * b00 + a12 * b01 + a22 * b02;
                out[3] = a03 * b00 + a13 * b01 + a23 * b02;
                out[4] = a00 * b10 + a10 * b11 + a20 * b12;
                out[5] = a01 * b10 + a11 * b11 + a21 * b12;
                out[6] = a02 * b10 + a12 * b11 + a22 * b12;
                out[7] = a03 * b10 + a13 * b11 + a23 * b12;
                out[8] = a00 * b20 + a10 * b21 + a20 * b22;
                out[9] = a01 * b20 + a11 * b21 + a21 * b22;
                out[10] = a02 * b20 + a12 * b21 + a22 * b22;
                out[11] = a03 * b20 + a13 * b21 + a23 * b22;
            }
        };
        
        // 页面加载时初始化
        window.addEventListener('load', initWebGL);
    </script>
</body>
</html>

15.4.3 HTTP/3协议优势

HTTP/3特性介绍

HTTP/3是基于QUIC协议的下一代HTTP协议,提供了更好的性能和安全性。

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>HTTP/3协议演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .protocol-comparison {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .protocol-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #2196F3;
        }
        
        .protocol-card h3 {
            margin-top: 0;
            color: #2196F3;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        
        .feature-list li:before {
            content: "✓";
            color: #4CAF50;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .demo-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .test-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            margin: 10px 5px;
            font-size: 16px;
        }
        
        .test-button:hover {
            background-color: #45a049;
        }
        
        .test-button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        .results {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
            border-left: 4px solid #2196F3;
        }
        
        .performance-chart {
            width: 100%;
            height: 300px;
            border: 1px solid #ddd;
            margin: 20px 0;
        }
        
        .comparison-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .comparison-table th,
        .comparison-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        
        .comparison-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        
        .better {
            background-color: #e8f5e8;
            color: #2e7d32;
        }
        
        .worse {
            background-color: #ffebee;
            color: #c62828;
        }
    </style>
</head>
<body>
    <h1>HTTP/3协议特性演示</h1>
    
    <div class="protocol-comparison">
        <div class="protocol-card">
            <h3>HTTP/1.1</h3>
            <ul class="feature-list">
                <li>基于TCP协议</li>
                <li>队头阻塞问题</li>
                <li>多个连接开销大</li>
                <li>明文传输(可选HTTPS)</li>
                <li>缓存控制有限</li>
            </ul>
        </div>
        
        <div class="protocol-card">
            <h3>HTTP/2</h3>
            <ul class="feature-list">
                <li>多路复用</li>
                <li>服务器推送</li>
                <li>头部压缩</li>
                <li>二进制帧</li>
                <li>流优先级</li>
            </ul>
        </div>
        
        <div class="protocol-card">
            <h3>HTTP/3</h3>
            <ul class="feature-list">
                <li>基于QUIC协议</li>
                <li>内置加密</li>
                <li>连接迁移</li>
                <li>0-RTT握手</li>
                <li>改进的拥塞控制</li>
            </ul>
        </div>
    </div>
    
    <div class="demo-section">
        <h2>HTTP/3性能测试</h2>
        <p>以下测试比较不同HTTP版本的性能特征:</p>
        
        <button class="test-button" onclick="testConnectionSpeed()">测试连接速度</button>
        <button class="test-button" onclick="testMultiplexing()">测试多路复用</button>
        <button class="test-button" onclick="testHandshake()">测试握手时间</button>
        <button class="test-button" onclick="testMigration()">测试连接迁移</button>
        
        <div id="testResults" class="results" style="display: none;">
            <h3>测试结果</h3>
            <div id="testOutput"></div>
        </div>
        
        <canvas id="performanceChart" class="performance-chart"></canvas>
    </div>
    
    <div class="demo-section">
        <h2>协议特性对比</h2>
        
        <table class="comparison-table">
            <thead>
                <tr>
                    <th>特性</th>
                    <th>HTTP/1.1</th>
                    <th>HTTP/2</th>
                    <th>HTTP/3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>传输协议</td>
                    <td>TCP</td>
                    <td>TCP</td>
                    <td class="better">QUIC (UDP)</td>
                </tr>
                <tr>
                    <td>多路复用</td>
                    <td class="worse">❌</td>
                    <td class="better">✅</td>
                    <td class="better">✅</td>
                </tr>
                <tr>
                    <td>头部压缩</td>
                    <td class="worse">❌</td>
                    <td class="better">HPACK</td>
                    <td class="better">QPACK</td>
                </tr>
                <tr>
                    <td>服务器推送</td>
                    <td class="worse">❌</td>
                    <td class="better">✅</td>
                    <td class="better">✅</td>
                </tr>
                <tr>
                    <td>连接迁移</td>
                    <td class="worse">❌</td>
                    <td class="worse">❌</td>
                    <td class="better">✅</td>
                </tr>
                <tr>
                    <td>0-RTT握手</td>
                    <td class="worse">❌</td>
                    <td class="worse">❌</td>
                    <td class="better">✅</td>
                </tr>
                <tr>
                    <td>内置加密</td>
                    <td class="worse">可选</td>
                    <td class="worse">可选</td>
                    <td class="better">必需</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div class="demo-section">
        <h2>HTTP/3实际应用</h2>
        
        <h3>检测HTTP/3支持</h3>
        <button class="test-button" onclick="checkHTTP3Support()">检测浏览器支持</button>
        <button class="test-button" onclick="testHTTP3Request()">测试HTTP/3请求</button>
        
        <div id="supportResults" class="results" style="display: none;">
            <div id="supportOutput"></div>
        </div>
    </div>

    <script>
        // HTTP/3支持检测
        async function checkHTTP3Support() {
            const resultsDiv = document.getElementById('supportResults');
            const outputDiv = document.getElementById('supportOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '检测中...';
            
            try {
                // 检查浏览器是否支持HTTP/3
                const supportInfo = {
                    userAgent: navigator.userAgent,
                    connection: navigator.connection ? {
                        effectiveType: navigator.connection.effectiveType,
                        downlink: navigator.connection.downlink,
                        rtt: navigator.connection.rtt
                    } : '不支持Connection API',
                    serviceWorker: 'serviceWorker' in navigator,
                    fetch: 'fetch' in window,
                    streams: 'ReadableStream' in window
                };
                
                // 尝试检测HTTP/3支持
                let http3Support = false;
                try {
                    const response = await fetch('/test', {
                        method: 'HEAD',
                        cache: 'no-cache'
                    });
                    
                    // 检查响应头中的协议信息
                    const protocol = response.headers.get('alt-svc');
                    if (protocol && protocol.includes('h3')) {
                        http3Support = true;
                    }
                } catch (error) {
                    console.log('HTTP/3检测请求失败:', error);
                }
                
                outputDiv.innerHTML = `
                    <h4>浏览器支持情况</h4>
                    <p><strong>用户代理:</strong> ${supportInfo.userAgent}</p>
                    <p><strong>网络连接:</strong> ${JSON.stringify(supportInfo.connection, null, 2)}</p>
                    <p><strong>Service Worker:</strong> ${supportInfo.serviceWorker ? '✅' : '❌'}</p>
                    <p><strong>Fetch API:</strong> ${supportInfo.fetch ? '✅' : '❌'}</p>
                    <p><strong>Streams API:</strong> ${supportInfo.streams ? '✅' : '❌'}</p>
                    <p><strong>HTTP/3支持:</strong> ${http3Support ? '✅' : '❌'}</p>
                    
                    <h4>HTTP/3兼容性</h4>
                    <p>• Chrome 87+: 部分支持</p>
                    <p>• Firefox 88+: 实验性支持</p>
                    <p>• Safari: 开发中</p>
                    <p>• Edge: 跟随Chrome</p>
                `;
                
            } catch (error) {
                outputDiv.innerHTML = `❌ 检测失败: ${error.message}`;
            }
        }
        
        // 测试HTTP/3请求
        async function testHTTP3Request() {
            const resultsDiv = document.getElementById('supportResults');
            const outputDiv = document.getElementById('supportOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '测试HTTP/3请求...';
            
            try {
                const testUrls = [
                    'https://quic.nginx.org/',
                    'https://www.google.com/',
                    'https://www.cloudflare.com/',
                    'https://www.facebook.com/'
                ];
                
                const results = [];
                
                for (const url of testUrls) {
                    try {
                        const start = performance.now();
                        const response = await fetch(url, {
                            method: 'HEAD',
                            mode: 'no-cors',
                            cache: 'no-cache'
                        });
                        const end = performance.now();
                        
                        results.push({
                            url: url,
                            status: response.status || 'no-cors',
                            time: (end - start).toFixed(2),
                            protocol: response.headers ? response.headers.get('alt-svc') : 'unknown'
                        });
                        
                    } catch (error) {
                        results.push({
                            url: url,
                            status: 'error',
                            time: 'N/A',
                            protocol: 'unknown',
                            error: error.message
                        });
                    }
                }
                
                outputDiv.innerHTML = `
                    <h4>HTTP/3请求测试结果</h4>
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr>
                                <th style="border: 1px solid #ddd; padding: 8px;">URL</th>
                                <th style="border: 1px solid #ddd; padding: 8px;">状态</th>
                                <th style="border: 1px solid #ddd; padding: 8px;">时间(ms)</th>
                                <th style="border: 1px solid #ddd; padding: 8px;">协议</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${results.map(result => `
                                <tr>
                                    <td style="border: 1px solid #ddd; padding: 8px;">${result.url}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px;">${result.status}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px;">${result.time}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px;">${result.protocol || 'unknown'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                `;
                
            } catch (error) {
                outputDiv.innerHTML = `❌ 测试失败: ${error.message}`;
            }
        }
        
        // 测试连接速度
        async function testConnectionSpeed() {
            const resultsDiv = document.getElementById('testResults');
            const outputDiv = document.getElementById('testOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '测试连接速度...';
            
            // 模拟不同协议的连接时间
            const protocols = ['HTTP/1.1', 'HTTP/2', 'HTTP/3'];
            const results = [];
            
            for (const protocol of protocols) {
                const start = performance.now();
                
                // 模拟不同协议的连接时间
                let delay;
                switch (protocol) {
                    case 'HTTP/1.1':
                        delay = 150 + Math.random() * 50; // 150-200ms
                        break;
                    case 'HTTP/2':
                        delay = 80 + Math.random() * 30; // 80-110ms
                        break;
                    case 'HTTP/3':
                        delay = 40 + Math.random() * 20; // 40-60ms
                        break;
                }
                
                await new Promise(resolve => setTimeout(resolve, delay));
                
                const end = performance.now();
                results.push({
                    protocol: protocol,
                    time: (end - start).toFixed(2)
                });
            }
            
            outputDiv.innerHTML = `
                <h4>连接速度测试结果</h4>
                ${results.map(result => `
                    <p><strong>${result.protocol}:</strong> ${result.time}ms</p>
                `).join('')}
                
                <p><strong>性能提升:</strong></p>
                <p>• HTTP/2 比 HTTP/1.1 快 ${((results[0].time / results[1].time - 1) * 100).toFixed(1)}%</p>
                <p>• HTTP/3 比 HTTP/2 快 ${((results[1].time / results[2].time - 1) * 100).toFixed(1)}%</p>
                <p>• HTTP/3 比 HTTP/1.1 快 ${((results[0].time / results[2].time - 1) * 100).toFixed(1)}%</p>
            `;
            
            drawPerformanceChart(results);
        }
        
        // 测试多路复用
        async function testMultiplexing() {
            const resultsDiv = document.getElementById('testResults');
            const outputDiv = document.getElementById('testOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '测试多路复用性能...';
            
            // 模拟多个并发请求
            const requestCount = 10;
            const results = [];
            
            // HTTP/1.1 - 串行请求
            const http1Start = performance.now();
            for (let i = 0; i < requestCount; i++) {
                await new Promise(resolve => setTimeout(resolve, 20 + Math.random() * 10));
            }
            const http1End = performance.now();
            
            // HTTP/2 - 并行请求
            const http2Start = performance.now();
            const http2Promises = [];
            for (let i = 0; i < requestCount; i++) {
                http2Promises.push(new Promise(resolve => setTimeout(resolve, 20 + Math.random() * 10)));
            }
            await Promise.all(http2Promises);
            const http2End = performance.now();
            
            // HTTP/3 - 改进的并行请求
            const http3Start = performance.now();
            const http3Promises = [];
            for (let i = 0; i < requestCount; i++) {
                http3Promises.push(new Promise(resolve => setTimeout(resolve, 15 + Math.random() * 8)));
            }
            await Promise.all(http3Promises);
            const http3End = performance.now();
            
            results.push(
                { protocol: 'HTTP/1.1', time: (http1End - http1Start).toFixed(2) },
                { protocol: 'HTTP/2', time: (http2End - http2Start).toFixed(2) },
                { protocol: 'HTTP/3', time: (http3End - http3Start).toFixed(2) }
            );
            
            outputDiv.innerHTML = `
                <h4>多路复用测试结果 (${requestCount}个并发请求)</h4>
                ${results.map(result => `
                    <p><strong>${result.protocol}:</strong> ${result.time}ms</p>
                `).join('')}
                
                <p><strong>并发性能提升:</strong></p>
                <p>• HTTP/2 比 HTTP/1.1 快 ${((results[0].time / results[1].time - 1) * 100).toFixed(1)}%</p>
                <p>• HTTP/3 比 HTTP/2 快 ${((results[1].time / results[2].time - 1) * 100).toFixed(1)}%</p>
            `;
            
            drawPerformanceChart(results);
        }
        
        // 测试握手时间
        async function testHandshake() {
            const resultsDiv = document.getElementById('testResults');
            const outputDiv = document.getElementById('testOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '测试握手时间...';
            
            // 模拟不同协议的握手时间
            const results = [
                { protocol: 'HTTP/1.1 + TLS', time: (120 + Math.random() * 30).toFixed(2) },
                { protocol: 'HTTP/2 + TLS', time: (100 + Math.random() * 25).toFixed(2) },
                { protocol: 'HTTP/3 (0-RTT)', time: (20 + Math.random() * 15).toFixed(2) }
            ];
            
            outputDiv.innerHTML = `
                <h4>握手时间测试结果</h4>
                ${results.map(result => `
                    <p><strong>${result.protocol}:</strong> ${result.time}ms</p>
                `).join('')}
                
                <p><strong>握手优化:</strong></p>
                <p>• HTTP/3的0-RTT握手大大减少了连接建立时间</p>
                <p>• 相比传统TLS握手,HTTP/3快了 ${((results[0].time / results[2].time - 1) * 100).toFixed(1)}%</p>
            `;
            
            drawPerformanceChart(results);
        }
        
        // 测试连接迁移
        async function testMigration() {
            const resultsDiv = document.getElementById('testResults');
            const outputDiv = document.getElementById('testOutput');
            
            resultsDiv.style.display = 'block';
            outputDiv.innerHTML = '测试连接迁移...';
            
            // 模拟网络切换场景
            const scenarios = [
                { name: 'WiFi到4G切换', http1: 'connection lost', http2: 'connection lost', http3: 'seamless' },
                { name: 'IP地址变化', http1: 'reconnect needed', http2: 'reconnect needed', http3: 'maintained' },
                { name: '网络中断恢复', http1: 'slow recovery', http2: 'slow recovery', http3: 'fast recovery' }
            ];
            
            outputDiv.innerHTML = `
                <h4>连接迁移测试结果</h4>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="border: 1px solid #ddd; padding: 8px;">场景</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">HTTP/1.1</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">HTTP/2</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">HTTP/3</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${scenarios.map(scenario => `
                            <tr>
                                <td style="border: 1px solid #ddd; padding: 8px;">${scenario.name}</td>
                                <td style="border: 1px solid #ddd; padding: 8px;">${scenario.http1}</td>
                                <td style="border: 1px solid #ddd; padding: 8px;">${scenario.http2}</td>
                                <td style="border: 1px solid #ddd; padding: 8px; background-color: #e8f5e8;">${scenario.http3}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
                
                <p><strong>连接迁移优势:</strong></p>
                <p>• HTTP/3支持连接迁移,网络切换时无需重新建立连接</p>
                <p>• 使用连接ID而非IP地址标识连接</p>
                <p>• 移动设备和网络环境变化时体验更好</p>
            `;
        }
        
        // 绘制性能图表
        function drawPerformanceChart(data) {
            const canvas = document.getElementById('performanceChart');
            const ctx = canvas.getContext('2d');
            
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 设置样式
            ctx.font = '16px Arial';
            ctx.fillStyle = '#333';
            
            // 绘制标题
            ctx.fillText('协议性能对比', 20, 30);
            
            // 绘制柱状图
            const barWidth = 80;
            const barSpacing = 120;
            const startX = 100;
            const maxHeight = 200;
            
            // 找出最大值用于缩放
            const maxTime = Math.max(...data.map(d => parseFloat(d.time)));
            
            data.forEach((item, index) => {
                const barHeight = (parseFloat(item.time) / maxTime) * maxHeight;
                const x = startX + index * barSpacing;
                const y = 250 - barHeight;
                
                // 绘制柱状图
                const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1'];
                ctx.fillStyle = colors[index % colors.length];
                ctx.fillRect(x, y, barWidth, barHeight);
                
                // 绘制数值
                ctx.fillStyle = '#333';
                ctx.fillText(item.time + 'ms', x + 10, y - 10);
                
                // 绘制协议名称
                ctx.fillText(item.protocol, x, 280);
            });
            
            // 绘制坐标轴
            ctx.strokeStyle = '#ddd';
            ctx.beginPath();
            ctx.moveTo(80, 250);
            ctx.lineTo(600, 250);
            ctx.stroke();
        }
        
        // 页面加载时检查支持
        window.addEventListener('load', function() {
            console.log('HTTP/3演示页面已加载');
            
            // 自动检查支持
            setTimeout(checkHTTP3Support, 1000);
        });
    </script>
</body>
</html>

15.4.4 其他新兴技术

边缘计算和WebGPU

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>新兴Web技术展示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8f9fa;
        }
        
        .tech-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .tech-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
        }
        
        .tech-card h3 {
            color: #007bff;
            margin-top: 0;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }
        
        .experimental {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .available {
            background-color: #d4edda;
            color: #155724;
        }
        
        .development {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .demo-button {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        
        .demo-button:hover {
            background-color: #218838;
        }
        
        .demo-results {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
            border-left: 4px solid #28a745;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        
        .feature-list li:before {
            content: "→";
            color: #007bff;
            font-weight: bold;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>新兴Web技术展示</h1>
    <p>探索Web平台的前沿技术和未来发展方向</p>
    
    <div class="tech-grid">
        <div class="tech-card">
            <h3>WebGPU <span class="status-badge experimental">实验性</span></h3>
            <p>WebGPU是新一代GPU API,为Web带来现代图形和计算能力。</p>
            
            <ul class="feature-list">
                <li>硬件加速计算</li>
                <li>现代图形渲染</li>
                <li>并行计算支持</li>
                <li>机器学习加速</li>
            </ul>
            
            <button class="demo-button" onclick="testWebGPU()">测试WebGPU</button>
            <div id="webgpuResults" class="demo-results" style="display: none;"></div>
        </div>
        
        <div class="tech-card">
            <h3>WebCodecs <span class="status-badge experimental">实验性</span></h3>
            <p>WebCodecs为Web提供低级别的音视频编解码能力。</p>
            
            <ul class="feature-list">
                <li>硬件加速编解码</li>
                <li>低延迟处理</li>
                <li>自定义编解码器</li>
                <li>流媒体优化</li>
            </ul>
            
            <button class="demo-button" onclick="testWebCodecs()">测试WebCodecs</button>
            <div id="webCodecsResults" class="demo-results" style="display: none;"></div>
        </div>
        
        <div class="tech-card">
            <h3>Web Locks API <span class="status-badge available">可用</span></h3>
            <p>Web Locks API提供了跨标签页和Worker的资源锁定机制。</p>
            
            <ul class="feature-list">
                <li>跨标签页同步</li>
                <li>资源互斥访问</li>
                <li>死锁检测</li>
                <li>超时处理</li>
            </ul>
            
            <button class="demo-button" onclick="testWebLocks()">测试Web Locks</button>
            <div id="webLocksResults" class="demo-results" style="display: none;"></div>
        </div>
        
        <div class="tech-card">
            <h3>Web Streams API <span class="status-badge available">可用</span></h3>
            <p>Web Streams API为Web提供了流式数据处理能力。</p>
            
            <ul class="feature-list">
                <li>流式数据处理</li>
                <li>背压控制</li>
                <li>可取消操作</li>
                <li>内存优化</li>
            </ul>
            
            <button class="demo-button" onclick="testWebStreams()">测试Web Streams</button>
            <div id="webStreamsResults" class="demo-results" style="display: none;"></div>
        </div>
        
        <div class="tech-card">
            <h3>Origin Private File System <span class="status-badge experimental">实验性</span></h3>
            <p>为Web应用提供私有的高性能文件系统访问。</p>
            
            <ul class="feature-list">
                <li>高性能文件操作</li>
                <li>私有存储空间</li>
                <li>流式文件访问</li>
                <li>大文件支持</li>
            </ul>
            
            <button class="demo-button" onclick="testOPFS()">测试OPFS</button>
            <div id="opfsResults" class="demo-results" style="display: none;"></div>
        </div>
        
        <div class="tech-card">
            <h3>Web Neural Network API <span class="status-badge development">开发中</span></h3>
            <p>为Web提供硬件加速的神经网络推理能力。</p>
            
            <ul class="feature-list">
                <li>硬件加速推理</li>
                <li>标准化API</li>
                <li>多平台支持</li>
                <li>隐私保护</li>
            </ul>
            
            <button class="demo-button" onclick="testWebNN()">测试WebNN</button>
            <div id="webNNResults" class="demo-results" style="display: none;"></div>
        </div>
    </div>
    
    <script>
        // 测试WebGPU
        async function testWebGPU() {
            const resultsDiv = document.getElementById('webgpuResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试WebGPU支持...';
            
            try {
                if (!navigator.gpu) {
                    throw new Error('WebGPU不支持');
                }
                
                const adapter = await navigator.gpu.requestAdapter();
                if (!adapter) {
                    throw new Error('无法获取GPU适配器');
                }
                
                const device = await adapter.requestDevice();
                
                resultsDiv.innerHTML = `
                    <h4>✅ WebGPU支持检测</h4>
                    <p><strong>适配器:</strong> ${adapter.name || 'Unknown'}</p>
                    <p><strong>设备:</strong> ${device.label || 'GPU Device'}</p>
                    <p><strong>特性:</strong> ${Array.from(device.features).join(', ') || 'None'}</p>
                    <p><strong>限制:</strong> 支持的最大缓冲区大小等</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `❌ WebGPU测试失败: ${error.message}`;
            }
        }
        
        // 测试WebCodecs
        async function testWebCodecs() {
            const resultsDiv = document.getElementById('webCodecsResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试WebCodecs支持...';
            
            try {
                const features = {
                    videoDecoder: 'VideoDecoder' in window,
                    videoEncoder: 'VideoEncoder' in window,
                    audioDecoder: 'AudioDecoder' in window,
                    audioEncoder: 'AudioEncoder' in window,
                    videoFrame: 'VideoFrame' in window,
                    audioData: 'AudioData' in window
                };
                
                resultsDiv.innerHTML = `
                    <h4>WebCodecs支持检测</h4>
                    <p><strong>视频解码器:</strong> ${features.videoDecoder ? '✅' : '❌'}</p>
                    <p><strong>视频编码器:</strong> ${features.videoEncoder ? '✅' : '❌'}</p>
                    <p><strong>音频解码器:</strong> ${features.audioDecoder ? '✅' : '❌'}</p>
                    <p><strong>音频编码器:</strong> ${features.audioEncoder ? '✅' : '❌'}</p>
                    <p><strong>VideoFrame:</strong> ${features.videoFrame ? '✅' : '❌'}</p>
                    <p><strong>AudioData:</strong> ${features.audioData ? '✅' : '❌'}</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `❌ WebCodecs测试失败: ${error.message}`;
            }
        }
        
        // 测试Web Locks
        async function testWebLocks() {
            const resultsDiv = document.getElementById('webLocksResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试Web Locks...';
            
            try {
                if (!navigator.locks) {
                    throw new Error('Web Locks API不支持');
                }
                
                const lockName = 'test-lock';
                const startTime = Date.now();
                
                await navigator.locks.request(lockName, async (lock) => {
                    // 模拟一些需要同步的操作
                    await new Promise(resolve => setTimeout(resolve, 100));
                    return 'locked operation completed';
                });
                
                const endTime = Date.now();
                
                resultsDiv.innerHTML = `
                    <h4>✅ Web Locks API测试</h4>
                    <p><strong>锁名称:</strong> ${lockName}</p>
                    <p><strong>执行时间:</strong> ${endTime - startTime}ms</p>
                    <p><strong>状态:</strong> 锁定操作成功完成</p>
                    <p><strong>用途:</strong> 跨标签页资源同步</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `❌ Web Locks测试失败: ${error.message}`;
            }
        }
        
        // 测试Web Streams
        async function testWebStreams() {
            const resultsDiv = document.getElementById('webStreamsResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试Web Streams...';
            
            try {
                if (!ReadableStream) {
                    throw new Error('ReadableStream不支持');
                }
                
                // 创建一个简单的流
                const stream = new ReadableStream({
                    start(controller) {
                        for (let i = 0; i < 5; i++) {
                            controller.enqueue(`chunk ${i}`);
                        }
                        controller.close();
                    }
                });
                
                const reader = stream.getReader();
                const chunks = [];
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    chunks.push(value);
                }
                
                resultsDiv.innerHTML = `
                    <h4>✅ Web Streams API测试</h4>
                    <p><strong>流类型:</strong> ReadableStream</p>
                    <p><strong>读取的块:</strong> ${chunks.join(', ')}</p>
                    <p><strong>支持特性:</strong> 流式数据处理</p>
                    <p><strong>应用场景:</strong> 大文件处理、实时数据</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `❌ Web Streams测试失败: ${error.message}`;
            }
        }
        
        // 测试Origin Private File System
        async function testOPFS() {
            const resultsDiv = document.getElementById('opfsResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试Origin Private File System...';
            
            try {
                if (!navigator.storage || !navigator.storage.getDirectory) {
                    throw new Error('Origin Private File System不支持');
                }
                
                const opfsRoot = await navigator.storage.getDirectory();
                
                // 创建一个文件
                const fileHandle = await opfsRoot.getFileHandle('test.txt', { create: true });
                const writable = await fileHandle.createWritable();
                
                await writable.write('Hello, OPFS!');
                await writable.close();
                
                // 读取文件
                const file = await fileHandle.getFile();
                const content = await file.text();
                
                resultsDiv.innerHTML = `
                    <h4>✅ Origin Private File System测试</h4>
                    <p><strong>文件名:</strong> test.txt</p>
                    <p><strong>文件内容:</strong> ${content}</p>
                    <p><strong>文件大小:</strong> ${file.size} bytes</p>
                    <p><strong>优势:</strong> 高性能私有文件系统</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `❌ OPFS测试失败: ${error.message}`;
            }
        }
        
        // 测试Web Neural Network API
        async function testWebNN() {
            const resultsDiv = document.getElementById('webNNResults');
            resultsDiv.style.display = 'block';
            resultsDiv.innerHTML = '测试Web Neural Network API...';
            
            try {
                // Web Neural Network API still in development
                if (!navigator.ml) {
                    throw new Error('Web Neural Network API不支持(仍在开发中)');
                }
                
                // 这里是假想的API使用示例
                const context = await navigator.ml.createContext();
                const model = await context.loadModel('simple-classifier');
                
                resultsDiv.innerHTML = `
                    <h4>✅ Web Neural Network API测试</h4>
                    <p><strong>上下文:</strong> ML Context创建成功</p>
                    <p><strong>模型:</strong> 简单分类器</p>
                    <p><strong>状态:</strong> 开发中,API可能变化</p>
                    <p><strong>用途:</strong> 浏览器内机器学习推理</p>
                `;
                
            } catch (error) {
                resultsDiv.innerHTML = `
                    <h4>❌ Web Neural Network API测试</h4>
                    <p><strong>状态:</strong> 仍在开发中</p>
                    <p><strong>说明:</strong> 这是一个提案阶段的API</p>
                    <p><strong>预期功能:</strong> 硬件加速的神经网络推理</p>
                    <p><strong>替代方案:</strong> 目前可使用TensorFlow.js</p>
                `;
            }
        }
        
        // 页面加载时显示技术概览
        window.addEventListener('load', function() {
            console.log('新兴Web技术展示页面已加载');
            
            // 显示浏览器兼容性信息
            const compatibilityInfo = document.createElement('div');
            compatibilityInfo.innerHTML = `
                <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin: 20px 0;">
                    <h3>浏览器兼容性说明</h3>
                    <p><strong>Chrome:</strong> 大部分新技术的首发平台</p>
                    <p><strong>Firefox:</strong> 渐进式支持新特性</p>
                    <p><strong>Safari:</strong> 选择性支持部分特性</p>
                    <p><strong>Edge:</strong> 跟随Chrome的发展</p>
                </div>
            `;
            
            document.body.appendChild(compatibilityInfo);
        });
    </script>
</body>
</html>

本节要点回顾

  • WebXR技术:了解虚拟现实和增强现实在Web上的实现
  • WebGL渲染:掌握3D图形渲染的基本原理和应用
  • HTTP/3协议:理解新协议带来的性能提升和特性优势
  • 新兴技术:探索WebGPU、WebCodecs等前沿技术的发展
  • 边缘计算:了解Web平台在边缘计算中的应用潜力
  • 未来趋势:把握Web技术的发展方向和创新机遇

相关学习资源

常见问题FAQ

Q: 这些新兴技术什么时候能够普及?

A: 不同技术的普及时间不同,WebGL已经广泛支持,WebXR正在逐步普及,而WebGPU等仍处于实验阶段。

Q: 如何跟上Web技术的最新发展?

A: 关注W3C规范、浏览器更新日志、开发者社区讨论,以及技术会议和博客。

Q: 新兴技术对现有项目有什么影响?

A: 新技术通常是渐进式增强,可以在支持的浏览器中提供更好的体验,不会破坏现有功能。

Q: 是否需要为所有新技术做兼容性处理?

A: 根据项目需求和目标用户选择,优先考虑已经稳定和广泛支持的技术。

Q: 如何评估新技术的成熟度?

A: 查看浏览器支持情况、社区活跃度、规范稳定性和实际应用案例。


本章总结:第15章介绍了HTML5的未来发展方向,包括Web Components、PWA、WebAssembly和各种新兴技术,为开发者提供了技术发展的前瞻性视角。