经纬志
首页 / luma.gl / API 文档

Device

先看结论

设备是 GPU 资源的唯一入口:缓冲区、纹理、着色器、管线、渲染通道都由它创建。 v9 的设备是异步创建的,适配器需要显式传入,WebGL 后端还要同时给出画布。

最后验证 2026-11-03 · luma.gl 9.4 · 更新 2026-10-28 · 引用本文
luma.createDevice(props) → Promise<Device>

UMD 需要四个包

UMD 版本没有内置的适配器和引擎,只能按顺序补齐四段脚本: core 提供设备与资源类,webgl 提供 WebGL2 适配器, shadertools 提供着色器组装,engine 提供 Model 与 AnimationLoop。

<script src="https://cdn.jsdelivr.net/npm/@luma.gl/core@9.4.2/dist/dist.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@luma.gl/webgl@9.4.2/dist/dist.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@luma.gl/shadertools@9.4.2/dist/dist.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@luma.gl/engine@9.4.2/dist/dist.min.js"></script>

四段脚本共用一个全局对象 luma,创建设备的入口是 luma.luma.createDevice。ESM 版本写 import { luma } from '@luma.gl/core',没有这一层嵌套。

创建设备

const device = await luma.luma.createDevice({
  type: 'webgl',
  adapters: [luma.webgl2Adapter],
  createCanvasContext: {
    canvas: document.getElementById('cv'),
    useDevicePixels: Math.min(window.devicePixelRatio, 2),
    autoResize: true
  }
});

adapters 省略时,设备会去查找已注册的适配器;UMD 下没有任何注册, 省略的后果就是创建失败。把 webgl2Adapter 直接放进数组是最稳的写法。

创建参数

参数说明
typewebgl、webgpu、null,或 best-available 依次尝试 WebGPU 与 WebGL
adapters适配器数组,如 [luma.webgl2Adapter]
createCanvasContext画布配置,或传 true 表示新建默认画布
webgl透传给 canvas.getContext('webgl2', props.webgl) 的上下文属性
powerPreferencehigh-performance、low-power、default
onError错误回调,接收 Error 与上下文对象
debug打开实现相关的检查,出错时直接停在出错位置
debugShadersnever、errors、warnings、always,控制着色器源码的打印时机
debugFramebuffers把帧缓冲的小尺寸预览画到主画布上

成员

成员说明
type后端类型,WebGL 下为 'webgl'
handle底层句柄,WebGL 下即 WebGL2RenderingContext
info显卡与版本信息:vendor、renderer、version、gpu、shadingLanguage
features能力查询,has(name) 返回布尔值
limits各类上限,如纹理层数、绑定组数量、顶点属性数量
preferredColorFormat画布首选颜色格式
preferredDepthFormat首选深度格式,创建深度纹理时直接用这个值
canvasContext默认画布上下文,没有画布时为 null
isLost / lost是否已丢失,以及丢失时兑现的 Promise
timestamp单调递增的更新时间戳,用于判断资源是否变化

资源工厂

方法返回
createBuffer(props)Buffer
createTexture(props)Texture
createSampler(props)Sampler
createShader(props)Shader
createRenderPipeline(props)RenderPipeline
createFramebuffer(props)Framebuffer
createVertexArray(props)VertexArray
beginRenderPass(props)RenderPass
createCommandEncoder(props)CommandEncoder

读取运行信息

console.log(device.type);                // 'webgl'
console.log(device.info.renderer);       // 显卡型号
console.log(device.info.shadingLanguage);// 'glsl'
console.log(device.preferredDepthFormat);// 'depth24plus' 之类的深度格式
console.log(device.getMipLevelCount(512, 512));
console.log(device.isTextureFormatSupported('rgba8unorm'));

这些查询在运行期决定分支:深度格式决定帧缓冲的附件格式, 纹理格式决定能否上传浮点数据。写死格式的代码在部分显卡上会直接创建失败。

销毁

await device.lost;
device.destroy();

设备销毁后其创建的资源全部失效,继续使用会拿到空句柄。 上下文丢失时 lost 会兑现,需要重建设备并在回调里重新上传资源。

WebGL 后端只有一个画布。再调用 createCanvasContext 会抛错, 离线渲染要改用 Framebuffer;WebGPU 后端才支持同时挂多个画布。

引用本文

经纬志(2026)。《Device》。https://www.jingweizhi.com/lumagl/api/device.html(访问日期 2026-11-03)。