WebAssembly (WASM) for High Performance Apps · درس

إنشاء تطبيق WASM متكامل

طبّق جميع المعارف المكتسبة لتصميم وبناء تطبيق متطور وعالي الأداء يعمل بواسطة WebAssembly

الدرس 3 من 412 خطوة

إنشاء تطبيق WASM متكامل درس مجاني في WebAssembly (WASM) for High Performance Apps على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في WebAssembly (WASM) for High Performance Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة WebAssembly (WASM) for High Performance Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Building a Complete WASM App

You've learned the building blocks of WebAssembly. Now, let's bring it all together! A 'complete' WASM application integrates high-performance WASM code with a responsive JavaScript host, managing data, concurrency, and error handling effectively.

We'll explore how to architect such an application by applying what you've learned.

WASM App Blueprint

A typical high-performance WASM application involves several layers. The JavaScript host handles UI and high-level logic, while WASM modules perform intensive computation. For complex tasks, Web Workers can offload WASM execution to separate threads, preventing UI freezes. This layered approach ensures both speed and responsiveness.

  • JavaScript Host: UI, API calls, orchestrates WASM.
  • WASM Module(s): Core high-performance logic.
  • Web Workers: Background execution for non-blocking operations.
  • Shared Memory: Efficient data exchange between threads.

Setting Up Our Rust-WASM Project

For building a complete application, our Rust WASM project needs to be set up to compile efficiently and interact smoothly with JavaScript. We use wasm-pack to build our Rust code into a WASM module and wasm-bindgen to generate the necessary JavaScript glue code for seamless interoperability.

High-Performance Image Logic

Let's consider a simple image processing task: converting an image to grayscale. The computationally intensive part will live in our Rust WASM module. We'll write a function that takes a pointer to image data in WASM's linear memory and processes it directly.

Try running this simplified Rust example:

pub extern "C" fn apply_grayscale(ptr: *mut u8, len: usize) {
    let slice = unsafe {
        assert!(!ptr.is_null());
        std::slice::from_raw_parts_mut(ptr, len)
    };

    // Image data is typically RGBA, 4 bytes per pixel
    for i in (0..len).step_by(4) {
        let r = slice[i] as u32;
        let g = slice[i + 1] as u32;
        let b = slice[i + 2] as u32;
        let gray = ((r + g + b) / 3) as u8;

        slice[i] = gray;
        slice[i + 1] = gray;
        slice[i + 2] = gray;
        // Alpha channel (slice[i+3]) remains unchanged
    }
}

// A minimal main function for runnable context.
// In WASM, `apply_grayscale` would be directly called by JS.
fn main() {
    let mut image_data = [
        255, 0, 0, 255,   // Red pixel
        0, 255, 0, 255    // Green pixel
    ];
    let ptr = image_data.as_mut_ptr();
    let len = image_data.len();
    apply_grayscale(ptr, len);
    println!("Processed first pixel R: {} G: {} B: {}", image_data[0], image_data[1], image_data[2]);
}

JS to WASM: Image Data Input

To pass our image data (e.g., from a canvas ImageData) to the WASM module, JavaScript needs to write it into WASM's linear memory. This involves getting a pointer from WASM to a memory region, then copying the Uint8ClampedArray into it. wasm-bindgen often simplifies this, but direct memory access is key.

Try running this example:

// Helper to simulate WASM memory and function call
const wasmMemory = new WebAssembly.Memory({ initial: 1 }); // 1 page = 64KB
const wasmByteView = new Uint8ClampedArray(wasmMemory.buffer);

// Simulate the WASM function (simplified grayscale logic)
const mockApplyGrayscale = (ptr, len) => {
  for (let i = ptr; i < ptr + len; i += 4) {
    const r = wasmByteView[i];
    const g = wasmByteView[i + 1];
    const b = wasmByteView[i + 2];
    const gray = Math.floor((r + g + b) / 3);
    wasmByteView[i] = gray;
    wasmByteView[i + 1] = gray;
    wasmByteView[i + 2] = gray;
  }
};

// Our "wasmModule" for this example
const wasmModule = {
  apply_grayscale: mockApplyGrayscale,
  memory: wasmMemory
};

// Example imageData (RGBA, 2 pixels)
const originalImageData = new Uint8ClampedArray([
  200, 100, 50, 255, // Pixel 1: Orange-ish
  50, 150, 200, 255  // Pixel 2: Blue-ish
]);

// Copy original data to WASM memory (offset 0 for simplicity)
wasmByteView.set(originalImageData, 0);

console.log("Original data in WASM memory (first 8 bytes):");
console.log(Array.from(wasmByteView.slice(0, 8)));

// Call the "WASM" function
wasmModule.apply_grayscale(0, originalImageData.length);

console.log("Processed data in WASM memory (first 8 bytes):");
console.log(Array.from(wasmByteView.slice(0, 8)));

WASM to JS: Processed Output

After WASM processes the data, the results are already present in its linear memory. JavaScript can then read this modified data directly from the WebAssembly.Memory buffer. This avoids costly data copying, especially for large datasets like image buffers.

Try running this example:

// Continuing from the previous example where wasmByteView has processed data

// Helper to simulate WASM memory and function call
const wasmMemory = new WebAssembly.Memory({ initial: 1 }); // 1 page = 64KB
const wasmByteView = new Uint8ClampedArray(wasmMemory.buffer);

// Simulate the WASM function (simplified grayscale logic)
const mockApplyGrayscale = (ptr, len) => {
  for (let i = ptr; i < ptr + len; i += 4) {
    const r = wasmByteView[i];
    const g = wasmByteView[i + 1];
    const b = wasmByteView[i + 2];
    const gray = Math.floor((r + g + b) / 3);
    wasmByteView[i] = gray;
    wasmByteView[i + 1] = gray;
    wasmByteView[i + 2] = gray;
  }
};

// Our "wasmModule" for this example
const wasmModule = {
  apply_grayscale: mockApplyGrayscale,
  memory: wasmMemory
};

// Example imageData (RGBA, 2 pixels)
const originalImageData = new Uint8ClampedArray([
  200, 100, 50, 255, // Pixel 1: Orange-ish
  50, 150, 200, 255  // Pixel 2: Blue-ish
]);

// Copy original data to WASM memory (offset 0 for simplicity)
wasmByteView.set(originalImageData, 0);

// Call the "WASM" function
wasmModule.apply_grayscale(0, originalImageData.length);

// To get the processed image data back into a JS array:
const processedImageData = new Uint8ClampedArray(
  wasmByteView.slice(0, originalImageData.length)
);

console.log("Data read back into JS array (first 8 bytes):");
console.log(Array.from(processedImageData.slice(0, 8)));

Keeping UI Responsive with Workers

For heavy computations like image processing, running WASM directly on the main thread can block the UI. The solution is to offload these tasks to a Web Worker. The worker loads the WASM module and performs the computation, communicating results back to the main thread via messages.

This example shows the message passing concept:

// main.js (simulated)
const worker = {
  onmessage: null,
  postMessage: (msg, transfers) => {
    console.log("Main thread sends to worker:", msg.type);
    // Simulate worker receiving and responding
    setTimeout(() => {
      if (msg.type === 'processImage') {
        const imageData = new Uint8ClampedArray(msg.data.buffer);
        // Simulate WASM processing
        for (let i = 0; i < imageData.length; i += 4) {
          const r = imageData[i];
          const g = imageData[i + 1];
          const b = imageData[i + 2];
          const gray = Math.floor((r + g + b) / 3);
          imageData[i] = gray;
          imageData[i + 1] = gray;
          imageData[i + 2] = gray;
        }
        if (worker.onmessage) {
          worker.onmessage({ data: { type: 'imageProcessed', result: imageData }, transfers: [imageData.buffer] });
        }
      }
    }, 10);
  }
};

worker.onmessage = (event) => {
  if (event.data.type === 'imageProcessed') {
    console.log("Main thread receives from worker:", event.data.type);
    console.log("Processed image data (first 8 bytes):", Array.from(event.data.result.slice(0, 8)));
    // Update UI with processed image data
  }
};

function sendImageToWorker(imageData) {
  // Transferrable objects improve performance for large data
  worker.postMessage({ type: 'processImage', data: imageData }, [imageData.buffer]);
}

// Example call (in main.js context, after image loaded)
const demoImageData = new Uint8ClampedArray([200,100,50,255, 50,150,200,255]);
console.log("Original demo image data (first 8 bytes):", Array.from(demoImageData.slice(0, 8)));
sendImageToWorker(demoImageData);

Shared Memory for Concurrency

While Web Workers prevent UI blocking, transferring large amounts of data between the main thread and workers can still be a bottleneck. SharedArrayBuffer allows both threads to access the same block of memory simultaneously. This is crucial for truly parallel WASM computations that need to coordinate or share state.

  • One memory block: Accessible by main thread and all workers.
  • No copying: Eliminates data transfer overhead.
  • Atomics: Required for safe, synchronized access to shared memory.
  • Use case: Real-time simulations, complex multi-threaded algorithms.

Handling Errors Gracefully

In a complete application, robust error handling is vital. When an error occurs in WASM, it typically crashes the module. We need mechanisms to catch these and communicate them back to JavaScript. Strategies include returning specific error codes, exporting a WASM function to set an error state, or using wasm-bindgen's built-in error propagation for Rust Result types.

  • Return Codes: WASM function returns 0 for success, non-zero for error.
  • Error State: WASM exports a function to retrieve last error message.
  • wasm-bindgen Errors: Rust Result types can be automatically converted to JS exceptions.

Orchestrating the Full Workflow

Let's put all the pieces together for our grayscale application. Imagine a web page with an image:

  1. User uploads an image.
  2. JavaScript reads the image into an ImageData object.
  3. JS sends the ImageData (or its underlying Uint8ClampedArray) to a Web Worker.
  4. The Web Worker loads the WASM module.
  5. The Worker calls the WASM grayscale function, passing the image data pointer.
  6. WASM processes the image data in memory.
  7. The Worker receives the processed data (already in its memory view).
  8. The Worker sends the processed data back to the main thread.
  9. The main thread updates the canvas with the new ImageData.

This full cycle demonstrates a high-performance, non-blocking WASM application.

Integrated WASM Concepts

Consider a complex WebAssembly application that performs real-time video processing. It uses Rust compiled to WASM, interacts with JavaScript, and needs to maintain a responsive user interface. Which of the following strategies are crucial for building such an application effectively?

Building Robust WASM Apps

You've now seen how to bring together various WebAssembly concepts to build a sophisticated application. From architecting the interaction between JavaScript and WASM, to managing memory, leveraging Web Workers for concurrency, and ensuring robust error handling, these principles are key to developing high-performance, production-ready WASM solutions.

The future of WASM is about seamless integration and unlocking new levels of web application capability.

البدء مجانًا

تعلم WebAssembly (WASM) for High Performance Apps مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
12
الدروس
48

الأسئلة الشائعة

هل درس «إنشاء تطبيق WASM متكامل» مجاني؟

نعم — نص درس «إنشاء تطبيق WASM متكامل» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة WebAssembly (WASM) for High Performance Apps، انتقل إلى CoddyKit PRO. تتضمن دورة WebAssembly (WASM) for High Performance Apps 4 دروس في المجموع.

ماذا ستتعلم في «إنشاء تطبيق WASM متكامل»؟

طبّق جميع المعارف المكتسبة لتصميم وبناء تطبيق متطور وعالي الأداء يعمل بواسطة WebAssembly تتمرن على WebAssembly (WASM) for High Performance Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ WebAssembly (WASM) for High Performance Apps؟

لا تُشترط خبرة سابقة. WebAssembly (WASM) for High Performance Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «إنشاء تطبيق WASM متكامل»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس WebAssembly (WASM) for High Performance Apps هذا؟

نعم. كل درس في WebAssembly (WASM) for High Performance Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. نموذج مكوّنات WASM وواجهات API المستقبلية
  2. أدوات WASM المتقدمة ومنظومته
  3. إنشاء تطبيق WASM متكامل
  4. جمع القمامة وأنواع المراجع في WASM
← العودة إلى WebAssembly (WASM) for High Performance Apps