UNPKG

cdf

Version:

A library for creating oldschool demo-like animations with JavaScript

101 lines (86 loc) 3.2 kB
var utils = { TWO_PI : Math.PI * 2, DEG_TO_RAD : Math.PI/180, RAD_TO_DEG : 180 / Math.PI, PI_BY_TWO : Math.PI / 2, coordRotate: function (xyPair, angleInDegrees, pivot) { var cx = (pivot && pivot[0]) ? pivot[0] : 0; var cy = (pivot && pivot[1]) ? pivot[1] : 0; var sin = Math.sin(angleInDegrees * utils.DEG_TO_RAD); var cos = Math.cos(angleInDegrees * utils.DEG_TO_RAD); return [ (sin * (xyPair[0] - cx)) + (cos * (xyPair[1] - cy)) + cx, (sin * (xyPair[1] - cy)) - (cos * (xyPair[0] - cx)) + cy ] }, clamp: function(val, min,max){ return val <= min ? min : val >= max ? max : val; }, coordPair: function(pair, defaultValue){ if(pair === undefined) return defaultValue || [0,0]; if(typeof pair === 'number') return [pair,pair]; return pair; }, between: function(val, min, max){ return val >= min && val <= max; }, strokeFill: function(c, fillStyle, lineWidth, strokeStyle, closePath){ if(closePath) c.ctx.closePath(); if (lineWidth) c.ctx.lineWidth = lineWidth; if (fillStyle) c.ctx.fillStyle = fillStyle; if (strokeStyle) c.ctx.strokeStyle = strokeStyle; if (lineWidth && strokeStyle) c.ctx.stroke(); if (fillStyle) c.ctx.fill(); return c; }, inherit: function(BaseClass, constructor, prototype){ var ChildClass = function(){ constructor.apply(this, arguments); }; // BaseClass.apply(this, arguments); ChildClass.prototype = Object.create(BaseClass.prototype); for(var pmn in prototype) if(prototype.hasOwnProperty(pmn)) { ChildClass[pmn] = prototype[pmn]; } return ChildClass; }, eventer: function(obj){ obj.on = function(event, handler, once){ if(typeof handler !== "function")return; this.__eventHandlers = this.__eventHandlers || {}; this.__eventHandlers[event] = this.__eventHandlers[event] || []; this.__eventHandlers[event].push({ callback:handler, once: !!once }); this.__lastAssignedEvent = event; return this; }; obj.trigger = function(event, thisObj, args){ if(event === undefined) event = this.__lastAssignedEvent; if(!this.__eventHandlers || typeof this.__eventHandlers[event] === "undefined" || !this.__eventHandlers[event].forEach) return this; thisObj = thisObj || this; args = args || []; for(var i =0; i<this.__eventHandlers[event].length; i++){ var data = this.__eventHandlers[event][i]; if(data && data.callback){ data.callback.apply(thisObj, args); if(data.once){ delete this.__eventHandlers[event][i]; } } } return this; }; return obj; }, shorthands: function(){ require('inc/shorthands')(require('cdf')); } }; var requestAnimFrameOriginal = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; utils.frame = requestAnimFrameOriginal ? function (callback) { requestAnimFrameOriginal.call(window, callback); } : function (callback) { window.setTimeout(callback, 1000 / 60); }; module.exports = utils;