UNPKG

@thi.ng/canvas

Version:

Canvas creation & HDPI support helpers

45 lines (44 loc) 1.45 kB
const adaptiveCanvas2d = (width, height = width, parent, opts = {}) => { const canvas = document.createElement("canvas"); adaptDPI(canvas, width, height, opts.dpr); opts.pixelated && (canvas.style.imageRendering = "pixelated"); parent?.appendChild(canvas); return { canvas, ctx: canvas.getContext("2d", opts.ctx) }; }; const canvas2d = (width, height = width, parent, opts) => adaptiveCanvas2d(width, height, parent, { dpr: 1, ...opts }); const pixelCanvas2d = (width, height = width, parent, opts) => adaptiveCanvas2d(width, height, parent, { dpr: 1, pixelated: true, ...opts }); const offscreenCanvas2d = (width, height = width, opts) => { const canvas = new OffscreenCanvas(width, height); return { canvas, ctx: canvas.getContext("2d", opts) }; }; const imageCanvas = (img, width = img.width, height = img.height, parent, opts) => { const res = canvas2d(width, height, parent, opts); res.ctx.drawImage(img, 0, 0, res.canvas.width, res.canvas.height); return res; }; const adaptDPI = (canvas, width, height, dpr = window.devicePixelRatio || 1) => { if (dpr !== 1) { canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; } canvas.width = width * dpr; canvas.height = height * dpr; return dpr; }; const isHighDPI = () => (window.devicePixelRatio || 1) > 1; export { adaptDPI, adaptiveCanvas2d, canvas2d, imageCanvas, isHighDPI, offscreenCanvas2d, pixelCanvas2d };