Skip to content

Clamp rgb values to [0,1] #84

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

Merged
merged 2 commits into from
Aug 4, 2015
Merged
Changes from 1 commit
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
Prev Previous commit
Add a comment on clamping rgb() and rgba() colors.
  • Loading branch information
SimonSapin committed Aug 4, 2015
commit 1d9144af7deefd76b70b42d4bf49970729c9476f
29 changes: 19 additions & 10 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,32 +318,41 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result<Color, ()>
val.max(0.).min(1.)
}

let red: f32;
let green: f32;
let blue: f32;
let mut red: f32;
let mut green: f32;
let mut blue: f32;
if is_rgb {
// Either integers or percentages, but all the same type.
match try!(arguments.next()) {
Token::Number(ref v) if v.int_value.is_some() => {

red = clamp(v.value / 255.);
red = v.value / 255.;
try!(arguments.expect_comma());
green = clamp(try!(arguments.expect_integer()) as f32 / 255.);
green = try!(arguments.expect_integer()) as f32 / 255.;
try!(arguments.expect_comma());
blue = clamp(try!(arguments.expect_integer()) as f32 / 255.);
blue = try!(arguments.expect_integer()) as f32 / 255.;
}
Token::Percentage(ref v) => {
red = clamp(v.unit_value);
red = v.unit_value;
try!(arguments.expect_comma());
green = clamp(try!(arguments.expect_percentage()));
green = try!(arguments.expect_percentage());
try!(arguments.expect_comma());
blue = clamp(try!(arguments.expect_percentage()));
blue = try!(arguments.expect_percentage());
}
_ => return Err(())
};
// The spec says to clamp to the device gamut which may be wider than 0% ... 100%,
// but moz2d doesn’t seem to have any support for this, so let’s not bother.
// https://drafts.csswg.org/css-color/#rgb-functions
// https://github.com/servo/rust-cssparser/issues/76
red = clamp(red);
green = clamp(green);
blue = clamp(blue);
} else {
let hue = try!(arguments.expect_number()) / 360.;
let hue = hue - hue.floor();
// Saturation and lightness are clamped to 0% ... 100%
// regardless of device gamut:
// https://drafts.csswg.org/css-color/#the-hsl-notation
try!(arguments.expect_comma());
let saturation = clamp(try!(arguments.expect_percentage()));
try!(arguments.expect_comma());
Expand Down