MadLittleMods
10/13/2016 - 3:26 AM

Useful for coloing SVG's, https://codepen.io/noahblon/post/coloring-svgs-in-css-background-images

// See http://codepen.io/MadLittleMods/pen/ozyoXB

.foo-emulation {
	.filter-hue-rotate(#f00, 120deg);
	background-color: @filter-hue-rotate-return;
}

.foo-actual {
	background-color: #f00;
	filter: hue-rotate(120deg);
}

.foo-expected {
	background-color: #0f0;
}

.foo-compensated-value {
	.get-compensated-filter-value(#0f0);
	@filter-value: @get-compensated-filter-value-return;
	background-color: #f00;
	filter: @filter-value;
}
// https://gist.github.com/MadLittleMods/39f4cd9867fb12143ece2647de2283fb
// via JavaScript implementation by Camilo Martin, http://stackoverflow.com/a/29585579/796832
//
// @angle: in degrees
.filter-hue-rotate(@color, @angle) {
	@r: red(@color);
	@g: green(@color);
	@b: blue(@color);
	@clampedAngle: unit(mod(mod(@angle, 360) + 360, 360));
	
	// Hold your breath because what follows isn't flowers.
	
	// Identity matrix for RGB
	// red
	@matrix0: 1;
	@matrix1: 0;
	@matrix2: 0;
	// green
	@matrix3: 0;
	@matrix4: 1;
	@matrix5: 0;
	// blue
	@matrix6: 0;
	@matrix7: 0;
	@matrix8: 1;
	
	// Luminance coefficients.
	@lumR: 0.2126;
	@lumG: 0.7152;
	@lumB: 0.0722;
	
	// Hue rotate coefficients.
	@hueRotateR: 0.143;
	@hueRotateG: 0.140;
	@hueRotateB: 0.283;
	
	@cos: cos(@clampedAngle * pi() / 180);
	@sin: sin(@clampedAngle * pi() / 180);
	
	@matrix0: @lumR + (1 - @lumR) * @cos - @lumR * @sin;
	@matrix1: @lumG - @lumG * @cos - @lumG * @sin;
	@matrix2: @lumB - @lumB * @cos + (1 - @lumB) * @sin;
	
	@matrix3: @lumR - @lumR * @cos + @hueRotateR * @sin;
	@matrix4: @lumG + (1 - @lumG) * @cos + @hueRotateG * @sin;
	@matrix5: @lumB - @lumB * @cos - @hueRotateB * @sin;
	
	@matrix6: @lumR - @lumR * @cos - (1 - @lumR) * @sin;
	@matrix7: @lumG - @lumG * @cos + @lumG * @sin;
	@matrix8: @lumB + (1 - @lumB) * @cos + @lumB * @sin;
	
	@resultantR: round(max(0, min(255, (@matrix0 * @r + @matrix1 * @g + @matrix2 * @b))));
	@resultantG: round(max(0, min(255, (@matrix3 * @r + @matrix4 * @g + @matrix5 * @b))));
	@resultantB: round(max(0, min(255, (@matrix6 * @r + @matrix7 * @g + @matrix8 * @b))));

	@filter-hue-rotate-return: rgb(@resultantR, @resultantG, @resultantB);
}


.get-compensated-filter-value(@color, @from-color: #f00) {
	@color-hue: hue(@color);
	@color-saturation: saturation(@color);
	@color-brightness: lightness(@color);
	
	.filter-hue-rotate(@from-color, @color-hue);
	@color-from-filter: @filter-hue-rotate-return;
	cff: @color-from-filter;
	
	@color-from-filter-saturation: saturation(@color-from-filter);
	@color-from-filter-brightness: lightness(@color-from-filter);
	
	@compensated-saturation: 1 / (@color-from-filter-saturation / @color-saturation);
	@compensated-brightness: 1 / (@color-from-filter-brightness /  @color-brightness);
	
	@get-compensated-filter-value-return: ~"hue-rotate(@{color-hue}deg) saturate(@{compensated-saturation}) brightness(@{compensated-brightness})";
}