Skip to content

Commit

Permalink
Adding color change for background images (proposal)
Browse files Browse the repository at this point in the history
  • Loading branch information
ollimeier committed Nov 15, 2024
1 parent 7dd97e2 commit 7761721
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
21 changes: 20 additions & 1 deletion src/fontra/client/core/font-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,26 @@ export class FontController {
const imagePromise = new Promise((resolve, reject) => {
image.onload = (event) => resolve(image);
});
image.src = `data:image/${imageData.type};base64,${imageData.data}`;

// The following code makes white pixels transparent, this is needed for applying color.
// Reference: https://stackoverflow.com/questions/30438524/algorithm-to-make-image-white-and-transparent
const idata = imageData.data;
const data32 = new Uint32Array(imageData.data.buffer); // use uint32 view for speed
const len = data32.length;

for (const i = 0; i < len; i++) {
const px = data32[i]; // pixel
// is white? then knock it out
if (px === 0xffffffff) data32[i] = px = 0;
// extract alpha channel from a pixel
px = px & 0xff000000; // little-endian: ABGR
// any non-transparency? ie. alpha > 0
if (px) {
data32[i] = px | 0xffffff; // set this pixel to white, keep alpha level
}
}

image.src = `data:image/${imageData.type};base64,${idata}`;

return await imagePromise;
}
Expand Down
14 changes: 12 additions & 2 deletions src/fontra/views/editor/visualization-layer-definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
makeUPlusStringFromCodePoint,
parseSelection,
rgbaToCSS,
rgbaToHex,
round,
unionIndexSets,
withSavedState,
Expand Down Expand Up @@ -450,9 +451,18 @@ registerVisualizationLayerDefinition({
affine.dy
);
if (backgroundImage.color) {
// TODO: solve colorizing with backgroundImage.color
// For now: apply alpha
context.globalAlpha = backgroundImage.color.alpha;
const hexColor = rgbaToHex([
backgroundImage.color.red,
backgroundImage.color.green,
backgroundImage.color.blue,
backgroundImage.color.alpha,
]);
context.fillStyle = hexColor;
// The following code does do the color change, of the background is transparent.
// Reference: https://stackoverflow.com/questions/45706829/change-color-image-in-canvas
context.fillRect(0, 0, image.width, image.height);
context.globalCompositeOperation = "destination-in";
}
context.drawImage(image, 0, 0, image.width, image.height);
});
Expand Down

0 comments on commit 7761721

Please sign in to comment.