CanvasContext
Quick answer
CanvasContext abstracts a canvas for the device: it maps CSS size to drawing-buffer size, tracks the device pixel ratio, handles resizing and position, and hands back the framebuffer to render into. Create one with device.createCanvasContext and read its width and height instead of the DOM attributes.
device. createCanvasContext ( props ) → CanvasContext
Key points
- device.createCanvasContext accepts canvas, width, height and useDevicePixels.
- getCurrentFramebuffer() returns the framebuffer for the current canvas image.
- getMousePosition(event) converts client coordinates into canvas pixels.
Example
const device = await luma.luma.createDevice({
type: 'webgl',
adapters: [luma.webgl2Adapter],
createCanvasContext: {
canvas: 'map-canvas',
useDevicePixels: Math.min(window.devicePixelRatio, 2),
autoResize: true
}
});
const ctx = device.canvasContext;
console.log(ctx.getCSSSize()); // [800, 600]
console.log(ctx.getDrawingBufferSize()); // [1600, 1200],2 倍像素比
console.log(ctx.getDevicePixelRatio()); // 2canvas.addEventListener('click', function (e) {
const rect = canvas.getBoundingClientRect();
const cssPixel = [e.clientX - rect.left, e.clientY - rect.top];
const devicePixel = ctx.cssToDevicePixels(cssPixel, true);
onPick(devicePixel.x, devicePixel.y);
});
Notes
- A canvas supports only one device context, so a second createDevice on it fails.
- Reading canvas.width from the DOM element ignores the pixel-ratio scaling.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). CanvasContext. https://www.jingweizhi.com/en/lumagl/api/canvas-context.html (accessed 2026-11-03).