WebGL Interop

Sharing a Canvas Between WebGL and WebGPU Code

A canvas keeps its first context for life: after getContext('webgpu') succeeds, getContext('webgl2') on the same element returns null (tested). During a gradual migration, leave the old WebGL code on its own canvas, usually an OffscreenCanvas, and bring each finished frame into WebGPU in the task that drew it:

Copying a WebGL frame into the WebGPU canvas, then drawing on topJavaScript
context.configure({ device, format,                  // COPY_DST lets the copy land here
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST });
drawLegacyScene(gl);                                 // any WebGL code, on an OffscreenCanvas
device.queue.copyExternalImageToTexture({ source: gl.canvas },
  { texture: context.getCurrentTexture() }, [gl.canvas.width, gl.canvas.height]);
// then a render pass with loadOp: 'load' draws the WebGPU layer over the copied frame

In demos/ch04/shared-canvas.html, WebGL paints six covers with scissored clears and WebGPU copies them in, then rings book 4 in gold; the copy is a GPU-side blit, cheap enough for every frame. Where the layers never need to mix in one image, two stacked canvases (the WebGPU one with alphaMode: 'premultiplied', Alpha Modes) avoid the copy altogether.

Legacy WebGL code paints six covers on an OffscreenCanvas; WebGPU copies each frame into its canvas and rings book 4 in gold on topHTMLLive
<!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="300"></canvas>
  <canvas id="labels" width="600" height="300"></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);
}

// The legacy layer: plain WebGL, six covers painted with scissored clears.
const legacy = new OffscreenCanvas(600, 300);        // same size as the canvas: the copy never scales
const gl = legacy.getContext('webgl2', { preserveDrawingBuffer: true });
function drawLegacyScene(gl, t) {
  gl.disable(gl.SCISSOR_TEST);
  gl.clearColor(0.93, 0.91, 0.87, 1); gl.clear(gl.COLOR_BUFFER_BIT);
  gl.enable(gl.SCISSOR_TEST);
  const tints = [[0.12, 0.37, 0.55], [0.36, 0.25, 0.60], [0.71, 0.27, 0.18], [0.88, 0.60, 0.06], [0.25, 0.49, 0.23], [0.16, 0.62, 0.56]];
  tints.forEach((c, i) => {
    const h = 150 + 20 * Math.sin(t + i);          // the legacy scene animates too
    gl.scissor(34 + i * 92, 40, 70, h); gl.clearColor(...c, 1); gl.clear(gl.COLOR_BUFFER_BIT);
    gl.scissor(34 + i * 92, 40 + h * 0.6, 70, 14); gl.clearColor(0.96, 0.93, 0.84, 1); gl.clear(gl.COLOR_BUFFER_BIT);
  });
}
// The WebGPU layer: a ring drawn over the copied frame with loadOp 'load'.
const code = /* wgsl */ `
@group(0) @binding(0) var<uniform> time: f32;
@vertex fn vs(@builtin(vertex_index) v: u32) -> @builtin(position) vec4f {
  let p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[v];
  return vec4f(p, 0, 1);
}
@fragment fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f {
  let center = vec2f(34 + 3 * 92 + 35, 300 - 128);        // book 4 (index 3)
  let d = abs(length((pos.xy - center) / vec2f(1, 1.55)) - 56 - 3 * sin(time * 3));
  let a = clamp(4 - d, 0, 1);
  if (a <= 0) { discard; }
  return vec4f(1.0, 0.78, 0.2, 1) * a;                    // premultiplied gold
}`;

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,               // COPY_DST lets the copy land here
    usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST });
  const secondContext = canvas.getContext('webgl2');   // a canvas keeps its first context for life
  const module = device.createShaderModule({ code });
  const blend = { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' };
  const pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { module },
    fragment: { module, targets: [{ format, blend: { color: blend, alpha: blend } }] } });
  const time = device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
  const group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: time } }] });

  ink.font = '12px ui-monospace, monospace'; ink.fillStyle = '#222';
  ink.fillText(`webgl2 layer: ${gl ? 'OffscreenCanvas 600 x 300' : 'unavailable'}   canvas.getContext('webgl2') now: ${secondContext}`, 10, 20);
  ink.font = '11.5px system-ui, sans-serif'; ink.fillStyle = '#555';
  ink.fillText('Per frame: drawLegacyScene(gl), copyExternalImageToTexture() into getCurrentTexture(), then a', 10, 280);
  ink.fillText("render pass with loadOp: 'load' draws the WebGPU layer on top.", 10, 296);

  function frame(now) {
    const texture = context.getCurrentTexture();
    if (gl) {
      drawLegacyScene(gl, now / 800);                // any WebGL code, in the same task as the copy
      device.queue.copyExternalImageToTexture({ source: legacy }, { texture }, [600, 300]);
    }
    device.queue.writeBuffer(time, 0, new Float32Array([now / 1000]));
    const encoder = device.createCommandEncoder();
    const pass = encoder.beginRenderPass({ colorAttachments: [{ view: texture.createView(), loadOp: 'load', storeOp: 'store' }] });
    pass.setPipeline(pipeline); pass.setBindGroup(0, group); pass.draw(3);
    pass.end();
    device.queue.submit([encoder.finish()]);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}
main();
</script>