UNPKG

@thi.ng/webgl

Version:

WebGL & GLSL abstraction layer

65 lines (64 loc) 1.85 kB
import { adaptDPI } from "@thi.ng/canvas"; import { isString } from "@thi.ng/checks/is-string"; import { error } from "./error.js"; const DEFAULT_OPTS = { alpha: true, antialias: true, depth: true, premultipliedAlpha: true, preserveDrawingBuffer: false, stencil: false }; const glCanvas = (opts = {}) => { const canvas = opts.canvas ? isString(opts.canvas) ? document.getElementById(opts.canvas) : opts.canvas : document.createElement("canvas"); opts.width && (canvas.width = opts.width); opts.height && (canvas.height = opts.height); opts.autoScale !== false && adaptDPI(canvas, canvas.width, canvas.height); opts.parent?.appendChild(canvas); const gl = canvas.getContext( opts.version !== 1 ? "webgl2" : "webgl", { ...DEFAULT_OPTS, ...opts.opts } ); if (!gl) { error("WebGL unavailable"); } opts.onContextLost && canvas.addEventListener("webglcontextlost", opts.onContextLost); return { canvas, gl, ext: getExtensions(gl, opts.ext), resize: (width, height) => { adaptDPI( canvas, width, height, opts.autoScale !== false ? window.devicePixelRatio : 1 ); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } }; }; const getExtensions = (gl, ids, required = true) => { const ext = {}; if (ids) { for (let id of ids) { ext[id] = gl.getExtension(id); required && !ext[id] && error(`extension ${id} not available`); } } return ext; }; const clearCanvas = (gl, [r, g, b, a], depth = true) => { gl.clearColor(r, g, b, a != null ? a : 1); gl.clear(gl.COLOR_BUFFER_BIT | (depth ? gl.DEPTH_BUFFER_BIT : 0)); }; const defaultViewport = (gl) => gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); export { clearCanvas, defaultViewport, getExtensions, glCanvas };