Canvas, sizing and device pixel ratio
Quick answer
This tutorial separates the CSS size of a canvas from its drawing-buffer size and shows how the device pixel ratio connects them. It configures createCanvasContext with canvas, useDevicePixels capped at two and autoResize, explains why CSS width and height must be authored, and reads props.width and props.height from AnimationLoop for aspect. It also rebuilds offscreen framebuffers when the viewport changes. Readers can avoid blurry, stretched or misaligned rendering.
Key points
- Pass useDevicePixels as Math.min(devicePixelRatio, 2) to cap buffer size.
- Give the canvas CSS width and height, because luma.gl only sets the drawing buffer.
- Compute aspect from props.width and props.height, which are device pixels.
Example
const device = await luma.luma.createDevice({
type: 'webgl',
adapters: [luma.webgl2Adapter],
createCanvasContext: {
canvas: document.getElementById('cv'),
useDevicePixels: Math.min(window.devicePixelRatio, 2),
autoResize: true
}
});html, body { height: 100%; margin: 0; }
#cv {
display: block;
width: 100%;
height: 100%;
touch-action: none; /* 触摸设备上不让页面抢走手势 */
}
Notes
- Pointer events arrive in CSS pixels and must be scaled before picking.
- A hidden container collapses the buffer to 1 by 1 and needs a resize on return.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Canvas, sizing and device pixel ratio. https://www.jingweizhi.com/en/lumagl/tutorials/canvas-sizing.html (accessed 2026-11-03).