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

feat: add ability to make color using css named string #524

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
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
24 changes: 24 additions & 0 deletions examples/fancycolor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
kaplay();

const COLORS = ["indianred", "lightcoral", "salmon", "darksalmon", "lightsalmon", "crimson", "red", "darkred", "pink", "lightpink", "hotpink", "deeppink", "mediumvioletred", "palevioletred", "coral", "tomato", "orangered", "darkorange", "orange", "gold", "yellow", "lightyellow", "lemonchiffon", "lightgoldenrodyellow", "papayawhip", "moccasin", "peachpuff", "palegoldenrod", "khaki", "darkkhaki", "lavender", "thistle", "plum", "violet", "orchid", "fuchsia", "magenta", "mediumorchid", "mediumpurple", "rebeccapurple", "blueviolet", "darkviolet", "darkorchid", "darkmagenta", "purple", "indigo", "slateblue", "darkslateblue", "mediumslateblue", "greenyellow", "chartreuse", "lawngreen", "lime", "limegreen", "palegreen", "lightgreen", "mediumspringgreen", "springgreen", "mediumseagreen", "seagreen", "forestgreen", "green", "darkgreen", "yellowgreen", "olivedrab", "olive", "darkolivegreen", "mediumaquamarine", "darkseagreen", "lightseagreen", "darkcyan", "teal", "aqua", "cyan", "lightcyan", "paleturquoise", "aquamarine", "turquoise", "mediumturquoise", "darkturquoise", "cadetblue", "steelblue", "lightsteelblue", "powderblue", "lightblue", "skyblue", "lightskyblue", "deepskyblue", "dodgerblue", "cornflowerblue", "royalblue", "blue", "mediumblue", "darkblue", "navy", "midnightblue", "cornsilk", "blanchedalmond", "bisque", "navajowhite", "wheat", "burlywood", "tan", "rosybrown", "sandybrown", "goldenrod", "darkgoldenrod", "peru", "chocolate", "saddlebrown", "sienna", "brown", "maroon", "white", "snow", "honeydew", "mintcream", "azure", "aliceblue", "ghostwhite", "whitesmoke", "seashell", "beige", "oldlace", "floralwhite", "ivory", "antiquewhite", "linen", "lavenderblush", "mistyrose", "gainsboro", "lightgray", "silver", "darkgray", "gray", "dimgray", "lightslategray", "slategray", "darkslategray", "black"];

const header = add([
text("look at all the fancy color names you have"),
pos(10, 10),
color("black")
])

const SIZE = vec2(50, 50);
var position = vec2(0, header.pos.y + header.height);
for (var i = 0; i < COLORS.length; i++) {
add([
pos(position),
rect(SIZE.x, SIZE.y),
color(COLORS[i])
]);
position = position.add(SIZE.x, 0);
if ((position.x + SIZE.x) > width()) {
position.x = 0;
position.y += SIZE.y;
}
}
18 changes: 9 additions & 9 deletions examples/ghosthunting.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,31 +63,31 @@ add([
rect(20, height()),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
add([
pos(0, 0),
rect(width(), 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
add([
pos(width() - 20, 0),
rect(20, height()),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
add([
pos(0, height() - 20),
rect(width(), 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
// Hallway
Expand All @@ -102,7 +102,7 @@ add([
rect(600, 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
// Living room
Expand All @@ -123,23 +123,23 @@ add([
rect(300, 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
add([
pos(420, 440),
rect(300, 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
add([
pos(820, 440),
rect(300, 20),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
// Kitchen
Expand All @@ -160,7 +160,7 @@ add([
rect(20, 288),
area(),
body({ isStatic: true }),
color(rgb(128, 128, 128)),
color("gray"),
"wall",
]);
// Storage
Expand Down
12 changes: 6 additions & 6 deletions examples/shooter.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ scene("battle", () => {

const sky = add([
rect(width(), height()),
color(0, 0, 0),
color(BLACK),
opacity(0),
]);

Expand All @@ -111,7 +111,7 @@ scene("battle", () => {
sky.opacity = 1;
}
else {
sky.color = rgb(0, 0, 0);
sky.color = BLACK;
sky.opacity = 0;
}
});
Expand Down Expand Up @@ -205,7 +205,7 @@ scene("battle", () => {
area(),
pos(p),
anchor("center"),
color(127, 127, 255),
color(rgb(127, 127, 255)),
outline(4),
move(UP, BULLET_SPEED),
offscreen({ destroy: true }),
Expand Down Expand Up @@ -321,7 +321,7 @@ scene("battle", () => {
const healthbar = add([
rect(width(), 24),
pos(0, 0),
color(107, 201, 108),
color(rgb(107, 201, 108)),
fixed(),
{
max: BOSS_HEALTH,
Expand All @@ -334,7 +334,7 @@ scene("battle", () => {

healthbar.onUpdate(() => {
if (healthbar.flash) {
healthbar.color = rgb(255, 255, 255);
healthbar.color = WHITE;
healthbar.flash = false;
}
else {
Expand Down Expand Up @@ -362,7 +362,7 @@ scene("win", ({ time, boss }) => {

add([
sprite(boss),
color(255, 0, 0),
color(RED),
anchor("center"),
scale(8),
pos(width() / 2, height() / 2),
Expand Down
96 changes: 72 additions & 24 deletions src/math/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,51 @@ export class Color {
);
}

/**
* Tries both fromHex() and fromCSSString()
*/
static fromString(color: string): Color {
try {
// fromHex() allows stuff like "ff00ff"
// (without the leading #) which is not valid in CSS
// so handle it first
return Color.fromHex(color);
} catch (_) {
return Color.fromCSSString(color);
}
}

/**
* Parses the color in the same way as your browser parses CSS.
*
* You can use [color names](https://developer.mozilla.org/en-US/docs/Web/CSS/named-color) such as "tomato" and "firebrick",
* notations such as `hsl()` and `cmyk()`, and even advanced stuff
* like [`color-mix()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix).
* Do note that you are at the mercy of the browser, not all formats may be supported.
*
* You can find all of the available formats [at MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value), be sure to check
* the browser compatibility table if it sounds like a "weird" format.
*/
static fromCSSString(color: string): Color {
const ctx = new OffscreenCanvas(1, 1).getContext("2d");
if (!ctx)
throw new Error("Failed to create offscreen canvas context");
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
const c = Array.from(ctx.getImageData(0, 0, 1, 1).data.slice(0, 3));
if (c.every(ch => ch === 0)) {
// if it is invalid we get black
// check to see if it is really invalid or actually
// supposed to be black
// (from https://stackoverflow.com/a/48485007/23626926)
const s = new Option().style;
s.color = color;
if (s.color !== color.toLowerCase())
throw new RangeError(`"${color}" is not a valid CSS color`);
}
return Color.fromArray(c);
}

static RED = new Color(255, 0, 0);
static GREEN = new Color(0, 255, 0);
static BLUE = new Color(0, 0, 255);
Expand Down Expand Up @@ -232,30 +277,33 @@ export type ColorArgs =
| [];

export function rgb(...args: ColorArgs): Color {
if (args.length === 0) {
return new Color(255, 255, 255);
}
else if (args.length === 1) {
if (args[0] instanceof Color) {
// rgb(new Color(255, 255, 255))
return args[0].clone();
}
else if (typeof args[0] === "string") {
// rgb("#ffffff")
return Color.fromHex(args[0]);
}
else if (Array.isArray(args[0]) && args[0].length === 3) {
// rgb([255, 255, 255])
return Color.fromArray(args[0]);
}
}
else if (args.length === 2) {
if (args[0] instanceof Color) {
return args[0].clone();
}
}
else if (args.length === 3 || args.length === 4) {
return new Color(args[0], args[1], args[2]);
switch (args.length) {
case 0:
return Color.WHITE;
case 1:
if (args[0] instanceof Color) {
// rgb(new Color(255, 255, 255))
return args[0].clone();
}
else if (typeof args[0] === "string") {
// rgb("#ffffff")
// rgb("ffffff")
// rgb("white")
return Color.fromString(args[0]);
}
else if (Array.isArray(args[0]) && args[0].length === 3) {
// rgb([255, 255, 255])
return Color.fromArray(args[0]);
}
break;
case 2:
if (args[0] instanceof Color) {
return args[0].clone();
}
break;
case 3:
case 4:
return new Color(args[0], args[1], args[2]);
}

throw new Error("Invalid color arguments");
Expand Down