certainlyakey
3/4/2015 - 7:39 AM

Restylable SVG SASS mixin

Restylable SVG SASS mixin

//this mixin will produce a CSS property (for example background-image) which value will contain an encoded SVG with preset colors and properties 
//use http://codepen.io/yoksel/details/JDqvs/ to get URL encoded path
@mixin restylable-svg($encodedpath, $width, $height, $fill_color:black, $stroke_color:false, $stroke_width:1, $prop:'background-image') {
	// $fill_color: rgba($fill_color,.99);
	// $stroke_color: rgba($stroke_color,.99);
	$svgdata: '%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20%20%20width%3D%22' + $width + '%22%20height%3D%22' +$height + '%22%3E%0A%20%20%3Cpath%20d%3D%22';
	$stroke_attr: '';
	@if $stroke_color != false {
		$stroke_attr: '%20stroke%3D%22' + encodecolor($stroke_color) + '%22%20' + '%20stroke-width%3D%22' + $stroke_width + '%22%20';
	}
	$svgdata: $svgdata + $encodedpath + '%22' + $stroke_attr + '%20fill%3D%22' + encodecolor($fill_color) + '%22/%3E%0A%3C/svg%3E';
	#{$prop}: url('data:image/svg+xml,' + $svgdata);
}

//Helper functions

//from http://sassmeister.com/gist/1b4f2da5527830088e4d
@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

//requires str-replace function
@function encodecolor($string) {
	@if type-of($string) == 'color' {
        $string:inspect($string);
        $string:str-replace($string, '#', '%23');
        $string:str-replace($string, '(', '%28');
        $string:str-replace($string, ')', '%29');
        $string:str-replace($string, ',', '%2C');
    }
	@return $string;
}