Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use context2D to convert CSS4 colors to display-p3 #2145

Open
wants to merge 2 commits into
base: mbostock/raster-color-space
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions src/marks/raster.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,17 @@ export class Raster extends AbstractRaster {
// function, offset into the dense grid based on the current facet index.
else if (this.data == null && index) offset = index.fi * n;

// Color space and CSS4 color conversion
const colorBytes = converter(this.colorSpace);

// Render the raster grid to the canvas, blurring if needed.
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const context2d = canvas.getContext("2d", {colorSpace: this.colorSpace});
const image = context2d.createImageData(w, h);
const imageData = image.data;
let {r, g, b} = rgb(this.fill) ?? {r: 0, g: 0, b: 0};
let {r, g, b} = colorBytes(this.fill) ?? {r: 0, g: 0, b: 0};
let a = (this.fillOpacity ?? 1) * 255;
for (let i = 0; i < n; ++i) {
const j = i << 2;
Expand All @@ -144,7 +147,7 @@ export class Raster extends AbstractRaster {
imageData[j + 3] = 0;
continue;
}
({r, g, b} = rgb(fi));
({r, g, b} = colorBytes(fi));
}
if (FO) a = FO[i + offset] * 255;
imageData[j + 0] = r;
Expand Down Expand Up @@ -504,3 +507,23 @@ function denseY(y1, y2, width, height) {
}
};
}

// Color space and CSS4 conversions
export function converter(colorSpace) {
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
const context = canvas.getContext("2d", {colorSpace, willReadFrequently: true});
const mem = new Map();
const canvasConverter = (c) => {
if (mem.has((c = String(c)))) return mem.get(c);
context.fillStyle = c;
context.clearRect(0, 0, 1, 1);
context.fillRect(0, 0, 1, 1);
const [r, g, b] = context.getImageData(0, 0, 1, 1).data;
if (mem.size < 256) mem.set(c, {r, g, b});
return {r, g, b};
};
let p;
return colorSpace === "srgb" ? (c) => (isNaN((p = rgb(c)).opacity) ? canvasConverter(c) : p) : canvasConverter;
}
Loading