writeBuffer()

Writing Data with writeBuffer() and Mapped Ranges

Two ways fill a buffer from JavaScript. device.queue.writeBuffer(buffer, offset, data, dataOffset, size) copies a typed array or ArrayBuffer into the queue's timeline; it returns at once, and later work on the queue sees the data. mappedAtCreation: true instead hands you the memory before the GPU ever sees it:

Filling a new buffer through its mapped rangeJavaScript
const prices = [14.99, 39.50, 24.00, 18.75, 16.20, 21.30];
const buffer = device.createBuffer({ label: 'prices', size: prices.length * 4,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, mappedAtCreation: true });
new Float32Array(buffer.getMappedRange()).set(prices);
buffer.unmap();                                 // hands the memory to the GPU
device.queue.writeBuffer(buffer, 8, new Float32Array([22.50]));   // later: book 3's price

Both insist on 4-byte granularity: a mapped size of 6 threw a RangeError, a writeBuffer() offset of 2 failed validation ("BufferOffset (2) is not a multiple of 4"), and 6 bytes of data threw an OperationError. dataOffset and size count elements for typed arrays and bytes for an ArrayBuffer.

A price buffer filled through its mapped range, then updated live with writeBuffer() at 4-byte-aligned offsetsHTMLLive
<!doctype html>
<style>
  body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
  .stage { position: relative; width: 100%; max-width: 600px; }
  .stage canvas { display: block; width: 100%; }
  .stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
  <canvas id="view" width="600" height="340"></canvas>
  <canvas id="labels" width="600" height="340"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');

function showMessage(text) {                     // 2D fallback when WebGPU is missing
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}

const titles = ['Quiet Harbor', 'Small Steps', 'Salt and Saffron', "Clockmaker's", 'Night Trains', 'Paper Gardens'];
const code = /* wgsl */ `
@group(0) @binding(0) var<storage> prices: array<f32>;
@group(0) @binding(1) var<uniform> changed: u32;
struct Out { @builtin(position) pos: vec4f, @location(0) color: vec3f }
@vertex fn vs(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
  let q = vec2f(f32(v & 1), f32(v >> 1));
  let px = vec2f(30 + f32(i) * 92 + q.x * 70, 250 - q.y * prices[i] * 4.5);
  return Out(vec4f(px.x / 300 - 1, 1 - px.y / 170, 0, 1),
             select(vec3f(0.08, 0.40, 0.75), vec3f(0.88, 0.55, 0.15), i == changed));
}
@fragment fn fs(in: Out) -> @location(0) vec4f { return vec4f(in.color, 1); }`;

async function main() {
  const adapter = await navigator.gpu?.requestAdapter();
  if (!adapter) return showMessage('WebGPU is not available in this browser');
  const device = await adapter.requestDevice();
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });

  // 1. Fill a new buffer through its mapped range, before the GPU ever sees it.
  const prices = [14.99, 39.50, 24.00, 18.75, 16.20, 21.30];
  const buffer = device.createBuffer({ label: 'prices', size: prices.length * 4,
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, mappedAtCreation: true });
  new Float32Array(buffer.getMappedRange()).set(prices);
  buffer.unmap();                                   // hands the memory to the GPU

  // 2. The 4-byte rules: a JavaScript exception and a validation error.
  let mappedSix = 'accepted';
  device.pushErrorScope('validation');             // depending on the browser: exception or GPU error
  try { device.createBuffer({ size: 6, usage: GPUBufferUsage.COPY_DST, mappedAtCreation: true }); }
  catch (e) { mappedSix = `${e.name}: ${e.message}`; }
  const sixError = await device.popErrorScope();
  if (sixError) mappedSix = sixError.message.split('\n')[0];
  device.pushErrorScope('validation');
  device.queue.writeBuffer(buffer, 2, new Float32Array([1]));
  const offsetTwo = await device.popErrorScope();

  const changed = device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
  const module = device.createShaderModule({ code });
  const pipeline = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
    vertex: { module }, fragment: { module, targets: [{ format }] } });
  const group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
    { binding: 0, resource: { buffer } }, { binding: 1, resource: { buffer: changed } }] });

  let last = -1, book = 2, price = 22.50;
  function frame(now) {
    const tick = Math.floor(now / 1200);
    if (tick !== last) {                            // 3. later: one price changes in place
      last = tick;
      if (tick > 0) { book = (book + 1 + (tick * 7) % 5) % 6; price = 10 + ((tick * 37) % 30); }
      prices[book] = price;
      device.queue.writeBuffer(buffer, book * 4, new Float32Array([price]));  // offset: a multiple of 4
      device.queue.writeBuffer(changed, 0, new Uint32Array([book]));
    }
    const encoder = device.createCommandEncoder();
    const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
      clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, group);
    pass.draw(4, 6);
    pass.end();
    device.queue.submit([encoder.finish()]);

    ink.clearRect(0, 0, 600, 340);
    ink.fillStyle = '#222'; ink.font = 'bold 13px ui-monospace, monospace';
    ink.fillText(`writeBuffer(prices, ${book * 4}, new Float32Array([${price.toFixed(2)}]))`, 14, 24);
    ink.font = '11px system-ui, sans-serif'; ink.textAlign = 'center';
    titles.forEach((t, i) => { ink.fillStyle = '#333'; ink.fillText(t, 65 + i * 92, 266); ink.fillText(`$${prices[i].toFixed(2)}`, 65 + i * 92, 280); });
    ink.textAlign = 'left'; ink.fillStyle = '#8a2b2b'; ink.font = '11.5px ui-monospace, monospace';
    ink.fillText(`mapped size 6 -> ${mappedSix}`.slice(0, 84), 14, 306);
    ink.fillText(`writeBuffer offset 2 -> ${offsetTwo ? offsetTwo.message.split('\n')[0] : 'accepted'}`.slice(0, 84), 14, 324);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}
main();
</script>