Skip to content

Instantly share code, notes, and snippets.

@davidguttman
Created August 25, 2016 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidguttman/6cbf2d190680dd9020930f88ff16c02a to your computer and use it in GitHub Desktop.
Save davidguttman/6cbf2d190680dd9020930f88ff16c02a to your computer and use it in GitHub Desktop.
requirebin sketch
var lerp = require('lerp')
var ease = require('ease-component')
var createLoop = require('canvas-loop')
var createContext = require('2d-context')
var ctx = createContext()
var canvas = ctx.canvas
var app = createLoop(canvas)
app.start()
document.body.appendChild(canvas)
var nDots = 1000
var dots = createDots(nDots)
var maxAge = 20000
var time = 0
app.on('tick', function (dt) {
time += dt/1000
var width = app.shape[0]
var height = app.shape[1]
var wDot = 3
var hDot = wDot
ctx.fillStyle = 'rgba(20,20,20,0.8)'
ctx.fillRect(0,0,width,height)
dots.forEach(function (dot) {
dot.age += dt
var p = (dot.age % maxAge)/maxAge
var px = ease.inOutCube(p)
var py = ease.inOutSine(p)
var x0 = dot.seed * width
var x1 = score(dot) * width
var x = lerp(x0, x1, px)
var y = py * height
ctx.fillStyle = 'hsl('+[dot.h, dot.s+'%', dot.l+'%'].join(',')+')'
circle(ctx, x, y, wDot)
})
})
function createDots (n) {
var dots = []
for (var i = 0; i < n; i++) {
dots.push({
id: i,
age: 0 + Math.random() * 20000,
seed: bucketize(Math.random(), 10),
h: Math.floor(20 + Math.random() * 340),
s: Math.floor(25 + Math.random() * 75),
l: Math.floor(25 + Math.random() * 50)
})
}
return dots
}
function score (dot) {
return bucketize(dot.h/360, 10)
}
function bucketize (v, n) {
var v1 = Math.floor(v * n) / n
return (v + v1) / 2
}
function circle (ctx, x, y, d) {
var r = d/2
ctx.beginPath()
ctx.arc(x, y, d, 0, 2 * Math.PI, false)
ctx.fill()
ctx.closePath()
}
setTimeout(function(){require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=getCanvasContext;function getCanvasContext(type,opts){if(typeof type!=="string"){throw new TypeError("must specify type string")}opts=opts||{};if(typeof document==="undefined"&&!opts.canvas){return null}var canvas=opts.canvas||document.createElement("canvas");if(typeof opts.width==="number"){canvas.width=opts.width}if(typeof opts.height==="number"){canvas.height=opts.height}var attribs=opts;var gl;try{var names=[type];if(type.indexOf("webgl")===0){names.push("experimental-"+type)}for(var i=0;i<names.length;i++){gl=canvas.getContext(names[i],attribs);if(gl)return gl}}catch(e){gl=null}return gl||null}},{}],"2d-context":[function(require,module,exports){var getContext=require("get-canvas-context");module.exports=function get2DContext(opt){return getContext("2d",opt)}},{"get-canvas-context":1}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({"ease-component":[function(require,module,exports){exports.linear=function(n){return n};exports.inQuad=function(n){return n*n};exports.outQuad=function(n){return n*(2-n)};exports.inOutQuad=function(n){n*=2;if(n<1)return.5*n*n;return-.5*(--n*(n-2)-1)};exports.inCube=function(n){return n*n*n};exports.outCube=function(n){return--n*n*n+1};exports.inOutCube=function(n){n*=2;if(n<1)return.5*n*n*n;return.5*((n-=2)*n*n+2)};exports.inQuart=function(n){return n*n*n*n};exports.outQuart=function(n){return 1- --n*n*n*n};exports.inOutQuart=function(n){n*=2;if(n<1)return.5*n*n*n*n;return-.5*((n-=2)*n*n*n-2)};exports.inQuint=function(n){return n*n*n*n*n};exports.outQuint=function(n){return--n*n*n*n*n+1};exports.inOutQuint=function(n){n*=2;if(n<1)return.5*n*n*n*n*n;return.5*((n-=2)*n*n*n*n+2)};exports.inSine=function(n){return 1-Math.cos(n*Math.PI/2)};exports.outSine=function(n){return Math.sin(n*Math.PI/2)};exports.inOutSine=function(n){return.5*(1-Math.cos(Math.PI*n))};exports.inExpo=function(n){return 0==n?0:Math.pow(1024,n-1)};exports.outExpo=function(n){return 1==n?n:1-Math.pow(2,-10*n)};exports.inOutExpo=function(n){if(0==n)return 0;if(1==n)return 1;if((n*=2)<1)return.5*Math.pow(1024,n-1);return.5*(-Math.pow(2,-10*(n-1))+2)};exports.inCirc=function(n){return 1-Math.sqrt(1-n*n)};exports.outCirc=function(n){return Math.sqrt(1- --n*n)};exports.inOutCirc=function(n){n*=2;if(n<1)return-.5*(Math.sqrt(1-n*n)-1);return.5*(Math.sqrt(1-(n-=2)*n)+1)};exports.inBack=function(n){var s=1.70158;return n*n*((s+1)*n-s)};exports.outBack=function(n){var s=1.70158;return--n*n*((s+1)*n+s)+1};exports.inOutBack=function(n){var s=1.70158*1.525;if((n*=2)<1)return.5*(n*n*((s+1)*n-s));return.5*((n-=2)*n*((s+1)*n+s)+2)};exports.inBounce=function(n){return 1-exports.outBounce(1-n)};exports.outBounce=function(n){if(n<1/2.75){return 7.5625*n*n}else if(n<2/2.75){return 7.5625*(n-=1.5/2.75)*n+.75}else if(n<2.5/2.75){return 7.5625*(n-=2.25/2.75)*n+.9375}else{return 7.5625*(n-=2.625/2.75)*n+.984375}};exports.inOutBounce=function(n){if(n<.5)return exports.inBounce(n*2)*.5;return exports.outBounce(n*2-1)*.5+.5};exports["in-quad"]=exports.inQuad;exports["out-quad"]=exports.outQuad;exports["in-out-quad"]=exports.inOutQuad;exports["in-cube"]=exports.inCube;exports["out-cube"]=exports.outCube;exports["in-out-cube"]=exports.inOutCube;exports["in-quart"]=exports.inQuart;exports["out-quart"]=exports.outQuart;exports["in-out-quart"]=exports.inOutQuart;exports["in-quint"]=exports.inQuint;exports["out-quint"]=exports.outQuint;exports["in-out-quint"]=exports.inOutQuint;exports["in-sine"]=exports.inSine;exports["out-sine"]=exports.outSine;exports["in-out-sine"]=exports.inOutSine;exports["in-expo"]=exports.inExpo;exports["out-expo"]=exports.outExpo;exports["in-out-expo"]=exports.inOutExpo;exports["in-circ"]=exports.inCirc;exports["out-circ"]=exports.outCirc;exports["in-out-circ"]=exports.inOutCirc;exports["in-back"]=exports.inBack;exports["out-back"]=exports.outBack;exports["in-out-back"]=exports.inOutBack;exports["in-bounce"]=exports.inBounce;exports["out-bounce"]=exports.outBounce;exports["in-out-bounce"]=exports.inOutBounce},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({lerp:[function(require,module,exports){function lerp(v0,v1,t){return v0*(1-t)+v1*t}module.exports=lerp},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){var size=require("element-size");module.exports=fit;var scratch=new Float32Array(2);function fit(canvas,parent,scale){var isSVG=canvas.nodeName.toUpperCase()==="SVG";canvas.style.position=canvas.style.position||"absolute";canvas.style.top=0;canvas.style.left=0;resize.scale=parseFloat(scale||1);resize.parent=parent;return resize();function resize(){var p=resize.parent||canvas.parentNode;if(typeof p==="function"){var dims=p(scratch)||scratch;var width=dims[0];var height=dims[1]}else if(p&&p!==document.body){var psize=size(p);var width=psize[0]|0;var height=psize[1]|0}else{var width=window.innerWidth;var height=window.innerHeight}if(isSVG){canvas.setAttribute("width",width*resize.scale+"px");canvas.setAttribute("height",height*resize.scale+"px")}else{canvas.width=width*resize.scale;canvas.height=height*resize.scale}canvas.style.width=width+"px";canvas.style.height=height+"px";return resize}}},{"element-size":4}],4:[function(require,module,exports){module.exports=getSize;function getSize(element){if(element===window||element===document.body){return[window.innerWidth,window.innerHeight]}if(!element.parentNode){var temporary=true;document.body.appendChild(element)}var bounds=element.getBoundingClientRect();var styles=getComputedStyle(element);var height=(bounds.height|0)+parse(styles.getPropertyValue("margin-top"))+parse(styles.getPropertyValue("margin-bottom"));var width=(bounds.width|0)+parse(styles.getPropertyValue("margin-left"))+parse(styles.getPropertyValue("margin-right"));if(temporary){document.body.removeChild(element)}return[width,height]}function parse(prop){return parseFloat(prop)||0}},{}],5:[function(require,module,exports){var inherits=require("inherits");var EventEmitter=require("events").EventEmitter;var now=require("right-now");var raf=require("raf");module.exports=Engine;function Engine(fn){if(!(this instanceof Engine))return new Engine(fn);this.running=false;this.last=now();this._frame=0;this._tick=this.tick.bind(this);if(fn)this.on("tick",fn)}inherits(Engine,EventEmitter);Engine.prototype.start=function(){if(this.running)return;this.running=true;this.last=now();this._frame=raf(this._tick);return this};Engine.prototype.stop=function(){this.running=false;if(this._frame!==0)raf.cancel(this._frame);this._frame=0;return this};Engine.prototype.tick=function(){this._frame=raf(this._tick);var time=now();var dt=time-this.last;this.emit("tick",dt);this.last=time}},{events:1,inherits:6,raf:7,"right-now":9}],6:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],7:[function(require,module,exports){(function(global){var now=require("performance-now"),root=typeof window==="undefined"?global:window,vendors=["moz","webkit"],suffix="AnimationFrame",raf=root["request"+suffix],caf=root["cancel"+suffix]||root["cancelRequest"+suffix];for(var i=0;!raf&&i<vendors.length;i++){raf=root[vendors[i]+"Request"+suffix];caf=root[vendors[i]+"Cancel"+suffix]||root[vendors[i]+"CancelRequest"+suffix]}if(!raf||!caf){var last=0,id=0,queue=[],frameDuration=1e3/60;raf=function(callback){if(queue.length===0){var _now=now(),next=Math.max(0,frameDuration-(_now-last));last=next+_now;setTimeout(function(){var cp=queue.slice(0);queue.length=0;for(var i=0;i<cp.length;i++){if(!cp[i].cancelled){try{cp[i].callback(last)}catch(e){setTimeout(function(){throw e},0)}}}},Math.round(next))}queue.push({handle:++id,callback:callback,cancelled:false});return id};caf=function(handle){for(var i=0;i<queue.length;i++){if(queue[i].handle===handle){queue[i].cancelled=true}}}}module.exports=function(fn){return raf.call(root,fn)};module.exports.cancel=function(){caf.apply(root,arguments)};module.exports.polyfill=function(){root.requestAnimationFrame=raf;root.cancelAnimationFrame=caf}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"performance-now":8}],8:[function(require,module,exports){(function(process){(function(){var getNanoSeconds,hrtime,loadTime;if(typeof performance!=="undefined"&&performance!==null&&performance.now){module.exports=function(){return performance.now()}}else if(typeof process!=="undefined"&&process!==null&&process.hrtime){module.exports=function(){return(getNanoSeconds()-loadTime)/1e6};hrtime=process.hrtime;getNanoSeconds=function(){var hr;hr=hrtime();return hr[0]*1e9+hr[1]};loadTime=getNanoSeconds()}else if(Date.now){module.exports=function(){return Date.now()-loadTime};loadTime=Date.now()}else{module.exports=function(){return(new Date).getTime()-loadTime};loadTime=(new Date).getTime()}}).call(this)}).call(this,require("_process"))},{_process:2}],9:[function(require,module,exports){(function(global){module.exports=global.performance&&global.performance.now?function now(){return performance.now()}:Date.now||function now(){return+new Date}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],"canvas-loop":[function(require,module,exports){var fitter=require("canvas-fit");var loop=require("raf-loop");module.exports=function(canvas,opt){if(!canvas){throw new TypeError("must specify a canvas element")}opt=opt||{};var fit=fitter(canvas,opt.parent,opt.scale);var app=loop();var shape=[0,0];resize();window.addEventListener("resize",function(){resize();app.emit("resize")},false);Object.defineProperties(app,{scale:{get:function(){return fit.scale},set:function(s){fit.scale=s}},shape:{get:function(){return shape}},parent:{get:function(){return fit.parent},set:function(p){fit.parent=p}}});return app;function resize(){fit();var deviceWidth=canvas.width;var deviceHeight=canvas.height;shape[0]=deviceWidth/fit.scale;shape[1]=deviceHeight/fit.scale}}},{"canvas-fit":3,"raf-loop":5}]},{},[]);var lerp=require("lerp");var ease=require("ease-component");var createLoop=require("canvas-loop");var createContext=require("2d-context");var ctx=createContext();var canvas=ctx.canvas;var app=createLoop(canvas);app.start();document.body.appendChild(canvas);var nDots=1e3;var dots=createDots(nDots);var maxAge=2e4;var time=0;app.on("tick",function(dt){time+=dt/1e3;var width=app.shape[0];var height=app.shape[1];var wDot=3;var hDot=wDot;ctx.fillStyle="rgba(20,20,20,0.8)";ctx.fillRect(0,0,width,height);dots.forEach(function(dot){dot.age+=dt;var p=dot.age%maxAge/maxAge;var px=ease.inOutCube(p);var py=ease.inOutSine(p);var x0=dot.seed*width;var x1=score(dot)*width;var x=lerp(x0,x1,px);var y=py*height;ctx.fillStyle="hsl("+[dot.h,dot.s+"%",dot.l+"%"].join(",")+")";circle(ctx,x,y,wDot)})});function createDots(n){var dots=[];for(var i=0;i<n;i++){dots.push({id:i,age:0+Math.random()*2e4,seed:bucketize(Math.random(),10),h:Math.floor(20+Math.random()*340),s:Math.floor(25+Math.random()*75),l:Math.floor(25+Math.random()*50)})}return dots}function score(dot){return bucketize(dot.h/360,10)}function bucketize(v,n){var v1=Math.floor(v*n)/n;return(v+v1)/2}function circle(ctx,x,y,d){var r=d/2;ctx.beginPath();ctx.arc(x,y,d,0,2*Math.PI,false);ctx.fill();ctx.closePath()}},0);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"2d-context": "1.3.0",
"ease-component": "1.0.0",
"lerp": "1.0.3",
"canvas-loop": "1.0.7"
}
}
<!-- contents of this file will be placed inside the <body> -->
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment