diff --git a/README.md b/README.md index a07ca81f..1b688834 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,9 @@ html`` If you are using [2D Canvas](https://www.w3.org/TR/2dcontext/) (rather than [WebGL](https://webglfundamentals.org/)), you should use [DOM.context2d](#DOM_context2d) instead of DOM.canvas for automatic pixel density scaling. -# DOM.context2d(width, height[, dpi]) [<>](https://github.com/observablehq/stdlib/blob/main/src/dom/context2d.mjs "Source") +# DOM.context2d(width, height[, options]) [<>](https://github.com/observablehq/stdlib/blob/main/src/dom/context2d.mjs "Source") -Returns a new canvas context with the specified *width* and *height* and the specified device pixel ratio *dpi*. If *dpi* is not specified, it defaults to [*window*.devicePixelRatio](https://developer.mozilla.org/docs/Web/API/Window/devicePixelRatio). To access the context’s canvas, use [*context*.canvas](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas). For example, to create a 960×500 canvas: +Returns a new canvas context with the specified *width* and *height* and the specified *options*. The scale property of the options object defines the device pixel ratio, and defaults to [*window*.devicePixelRatio](https://developer.mozilla.org/docs/Web/API/Window/devicePixelRatio). The remaining options are passed through as contextAttributes to [getContext](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext). As a shorthand notation, *options* having only scale can be specified as a number. To access the context’s canvas, use [*context*.canvas](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas). For example, to create a 960×500 canvas: ```js { diff --git a/src/dom/context2d.mjs b/src/dom/context2d.mjs index 4b36ac89..5590091b 100644 --- a/src/dom/context2d.mjs +++ b/src/dom/context2d.mjs @@ -1,10 +1,15 @@ -export default function(width, height, dpi) { - if (dpi == null) dpi = devicePixelRatio; - var canvas = document.createElement("canvas"); - canvas.width = width * dpi; - canvas.height = height * dpi; +export default function (width, height, options = {}) { + const {scale = devicePixelRatio, ...contextOptions} = !isNaN(options) + ? {...(options != null && {scale: options})} + : options; + const canvas = document.createElement("canvas"); + canvas.width = width * scale; + canvas.height = height * scale; canvas.style.width = width + "px"; - var context = canvas.getContext("2d"); - context.scale(dpi, dpi); + const context = canvas.getContext( + "2d", + options === null ? options : contextOptions + ); + context.scale(scale, scale); return context; }