Canvas

@Composable
fun Canvas(modifier: SwingModifier = SwingModifier, onDraw: (g: Graphics2D, width: Int, height: Int) -> Unit)

A composable that hands you the raw Graphics2D of a blank Swing surface so you can draw whatever you like.

Repaint is snapshot-observed. Any snapshot state you read directly inside onDraw is tracked; when such state changes the surface repaints and re-invokes onDraw automatically. Read your state where you use it, at paint time:

var radius by remember { mutableStateOf(10) }
Canvas(modifier = SwingModifier.preferredSize(Dimension(200, 200))) { g, width, height ->
g.fillOval(width / 2 - radius, height / 2 - radius, radius * 2, radius * 2)
}

The surface is non-opaque and paints no background of its own: only what onDraw renders appears. Size it with the preferred-size modifier (see org.jetbrains.compose.swing.modifier.layout.preferredSize).

Parameters

modifier

the SwingModifier applied to the underlying component.

onDraw

receives the surface's Graphics2D and its current pixel width/height; called on the Swing event dispatch thread during painting. Do not retain the Graphics2D beyond the call.

See also