Chapter 02 · Java + TeaVM

Immediate pixels, direct browser API.

Use the same drawing primitives on an HTML Canvas, or drop down to TeaVM's CanvasRenderingContext2D for gradients and other native operations.

This chapter requires Canvas 2D support.

Starting the TeaVM application…

How it works

CanvasGraphics owns no retained scene. Each render call draws immediately. context() exposes the native TeaVM JSO context, while setSize() handles logical dimensions and device pixel ratio.

CanvasGraphics canvas = new CanvasGraphics(canvasElement);
canvas.setSize(960, 540, Window.current().getDevicePixelRatio());
CanvasGradient gradient = canvas.context()
    .createLinearGradient(0, 0, 960, 540);
gradient.addColorStop(0, "#102a42");
gradient.addColorStop(1, "#09111e");
canvas.context().setFillStyle(gradient);
canvas.context().fillRect(0, 0, 960, 540);