Skip to content

Instantly share code, notes, and snippets.

@roseg43
Created February 18, 2016 15:37
Show Gist options
  • Save roseg43/7b5ff37d86d664821369 to your computer and use it in GitHub Desktop.
Save roseg43/7b5ff37d86d664821369 to your computer and use it in GitHub Desktop.
Dynamic Slanted SVG-clip Banners
(function($) {
var index = 0;
var window_width = $('body').outerWidth();
$.fn.polygonMask = function(direction) {
var $this = $(this),
height = $this.outerHeight(),
offset_top = $this.offset().top;
/**
* Firefox automatically attaches SVG clip paths to the top of the parent element while Chrome attaches it to the window.
* To fix this, we're going to check if the user is using Firefox, and set the top offset to zero if they are.
*
* Reliable browser checking from: http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
**/
var isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox) {
offset_top = 0;
}
var directions = {
up: 60,
down: 60
};
var offset = directions[direction];
//SVG generation
var _svgNS = 'http://www.w3.org/2000/svg';
var svg = "<svg width='0' height='0' xmlns='http://www.w3.org/2000/svg' version='1.1'></svg>";
var defs = document.createElementNS(_svgNS, 'defs');
$this.append(svg);
$this.find('svg').append(defs);
var parent = $this.find('svg').get()[0];
var clippath = document.createElementNS(_svgNS, 'clipPath');
clippath.setAttributeNS(null, 'id', 'clip-' + index);
parent.appendChild(clippath);
height += offset_top;
offset += offset_top;
var points= [];
if (direction == "up") {
points[0] = "0 " + (offset);
}else{
points[0] = "0 " + offset_top;
}
points[1] = "0 " + (height);
points[2] = window_width + " " + height;
if (direction == 'up') {
points[3] = window_width + " " + offset_top;
}else {
points[3] = window_width + " " + offset;
}
var points_string = points.join(',');
console.log('ITEM ' + index + ': ' + points_string);
var polygon = document.createElementNS(_svgNS, 'polygon');
polygon.setAttribute("points", points_string);
clippath.appendChild(polygon);
$(this).css('-moz-clip-path', 'url(#clip-' + index + ')');
$(this).css('-webkit-clip-path', 'url(#clip-' + index + ')');
$(this).css('clip-path', 'url(#clip-' + index + ')');
index++;
};
})(jQuery);
$(function() {
$('.up').polygonMask('up');
$('.down').polygonMask('down');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment