WebGL interoperability
WebGL is a browser API for rendering hardware-accelerated 2D and 3D graphics. In a Compose Multiplatform app, you can use it for:
Custom graphics: draw shapes, animations, or shader effects.
JavaScript renderers: integrate existing JavaScript WebGL renderers to display 3D scenes or animated characters.
Other use cases include displaying video frames alongside Compose controls and overlays, or experimenting with HTML content as a texture through the HTML-in-Canvas API where the browser supports it.
Render a WebGL texture
A WebGLRenderTarget class lets you draw into a texture with WebGL and display the result in Compose through a Painter object. To render a WebGL texture:
Create a
WebGLRenderTargetinstance withrememberWebGLRenderTarget(). Specify the texture size using anIntSizein pixels or aDpSizein density-independent pixels.Draw using the target's
webGLContextinside atarget.render()block.Pass
target.painterto anImage()composable to display the result.
The API works with both Kotlin/Wasm and Kotlin/JS web targets. The following example updates a texture on each animation frame to produce a pulsing color and displays it inside an Image() composable. Add it to the wasmJsMain or jsMain source set, or to a shared webMain source set, and call ColorPulse() from your UI:
Integrate a JavaScript WebGL renderer
You can use an existing JavaScript WebGL renderer, such as three.js, to draw content for your Compose UI. The renderer shares the WebGL context with Compose and draws into the target's framebuffer. To use the renderer with a WebGLRenderTarget:
Define Kotlin bindings for the library using JavaScript interoperability for your web target: Kotlin/Wasm or Kotlin/JS.
Initialize the renderer with the target's
htmlCanvasandwebGLContext. Let Compose manage the canvas size and context lifetime.Draw into
target.framebufferinside atarget.render()block. If the renderer caches graphics state, reset that cache before drawing. For example, three.js providesrenderer.resetState()for this purpose.In the composable that owns the renderer, use
DisposableEffect()to release the renderer's resources when the composable leaves the composition. If cleanup modifies the shared WebGL context, calltarget.markGLStateStale()afterward.
The following example draws a frame using an initialized three.js renderer. Here, target is a WebGLRenderTarget; renderer, scene, and camera are your three.js objects; threeTarget is the render target for three.js, and its dimensions match target.size.
Clean up the renderer in the same composable: