Skip to content

Instantly share code, notes, and snippets.

@gnipbao
Created May 11, 2017 06:54
Show Gist options
  • Save gnipbao/378efa9d61566b081961d30d49620dbf to your computer and use it in GitHub Desktop.
Save gnipbao/378efa9d61566b081961d30d49620dbf to your computer and use it in GitHub Desktop.
ribbon effects
+ function() {
function attr(node, attr, default_value) {
return Number(node.getAttribute(attr)) || default_value;
}
// get user config
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1]; // 当前加载的script
config = {
z: attr(script, "zIndex", -1), // z-index
a: attr(script, "alpha", 0.6), // alpha
s: attr(script, "size", 90), // size
};
var canvas = document.createElement('canvas'), //画布
ctx = canvas.getContext('2d'), //2d对象
dpr = window.devicePixelRatio || 1, //设备像素比(物理像素 / dips)
width = window.innerWidth,
height = window.innerHeight,
f = config.s,
q, t,
m = Math, //alias 别名
r = 0,
pi = m.PI * 2,
cos = m.cos,
random = m.random;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.scale(dpr, dpr);
ctx.globalAlpha = config.a;
canvas.style.cssText = 'position:fixed;top:0;left:0;z-index: ' + config.z + ';width:100%;height:100%;pointer-events:none;';
// create canvas
document.getElementsByTagName('body')[0].appendChild(canvas);
function redraw() {
ctx.clearRect(0, 0, width, height);
q = [{
x: 0,
y: height * 0.7 + f
}, {
x: 0,
y: height * 0.7 - f
}];
console.log(q[0].x, q[0].y)
console.log(q[1].x, q[1].y)
while (q[1].x < width + f) draw(q[0], q[1]);
}
function draw(i, j) {
ctx.beginPath();
ctx.moveTo(i.x, i.y);
ctx.lineTo(j.x, j.y);
//随机生成下一点x:k,y:n
var k = j.x + (random() * 2 - 0.25) * f,
n = line(j.y);
ctx.lineTo(k, n);
console.log(`k->${k},n->${n}`);
ctx.closePath();
r -= pi / -50;
ctx.fillStyle = '#' + (cos(r) * 127 + 128 << 16 | cos(r + pi / 3) * 127 + 128 << 8 | cos(r + pi / 3 * 2) * 127 + 128).toString(16); //随机填充颜色
ctx.fill();
//以下一个为起点画三角
q[0] = q[1];
q[1] = {
x: k,
y: n
};
}
//随机生成下一点的y边界判断重新生成
function line(p) {
t = p + (random() * 2 - 1.1) * f;
return (t > height || t < 0) ? line(p) : t;
}
document.onclick = redraw;
document.ontouchstart = redraw;
redraw();
}();
/**
*<script type="text/javascript" size="10" alpha='0.3' zIndex="-2" src="./ribbon.js"></script>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment