Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate Scanlines with HTML5 Canvas and Javascript and apply CSS override to bottom of stylesheet to keep DOM clean of inline styles.
/*
* Created by Jordan Hess @jojohess
* http://robotvictory.com
*
* Usage:
* On Window Load/DOM ready, trigger:
*
* Plain JS:
* scanline('article.dark div.sub_block',"rgba(255,255,255,0.05)",3,'45');
*
* OR
*
* jQuery:
* $('article.dark div.sub_block').scanline({ color: 'rgba(255,255,255,0.05)', spacing: 3, direction: '45' });
*
* Enjoy!
});
*/
function scanline(sel,col,os,dir,lw) {
os=os||3;dir=dir||'45'; lw=lw||1;
var g, v = document.createElement('canvas'), n = v.getContext("2d"); v.width = os; v.height = os;
document.body.appendChild(v);
for (var x = 0; x <= os; x += os) {
var a=x,b=0,c=x,d=os;
switch (dir) {
case "0":
a = 0; b = x; c = os; d = x;
break;
case "45":
c = x-os;
break;
case "90":
break;
case "135":
a = x-os;
break;
default:
c = x-os;
}
n.moveTo(a, b);
n.lineTo(c, d);
}
n.lineWidth = lw; n.strokeStyle = col; n.stroke(); g = n.canvas.toDataURL();
try{document.styleSheets[0].insertRule(sel+"{background-image:url("+g+");}",document.styleSheets[0].cssRules.length);}catch(e){}
document.body.removeChild(v);
}
if(jQuery) (function($){
$.extend($.fn, {
scanline: function(o) {
var def = { color: '#fff', spacing: 3, direction: '45' }; o = $.extend(def, o);
scanline(this.selector,o.color,o.spacing,o.direction);
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment