observablehq / stdlib

The Observable standard library.
https://observablehq.com/@observablehq/standard-library
ISC License
966 stars 83 forks source link

Pass-through options from DOM.context2d to getContext #273

Open Fil opened 2 years ago

Fil commented 2 years ago

The third argument to DOM.context2d can be an options object with {scale, colorSpace}, allowing the creation of wide-gamut graphics on supported hardware and software.

Note: this necessitates a try/catch because Safari will throw if the os requirements are not met.

Tests/demo: https://observablehq.com/@fil/colorspace-display-p3-context2d

Draft, mostly for discussion.

Fil commented 2 years ago

It's fine to just do nothing. Easy enough to make this helper outside of stlib for special cases. (But it's very useful in general to not have to worry about dpr.)

Fil commented 2 years ago

we might want to document the willReadFrequently boolean option as well?

mootari commented 2 years ago

I believe the options handling can be simplified:

export default function(width, height, options = {}) {
  const {
    scale = devicePixelRatio,
    ...contextOptions
  } = !isNaN(options) ? {scale: options} : options;
  const canvas = document.createElement("canvas");
  canvas.width = width * scale;
  canvas.height = height * scale;
  canvas.style.width = width + "px";
  const context = canvas.getContext("2d", contextOptions);
  context.scale(scale, scale);
  return context;
}
Fil commented 1 year ago

Chrome (>= 111) supports display-p3 https://developer.chrome.com/articles/high-definition-css-color-guide/