Skip to content

Instantly share code, notes, and snippets.

View mattlundstrom's full-sized avatar

Matt Lundstrom mattlundstrom

View GitHub Profile
@mattlundstrom
mattlundstrom / snaptToIncrement.js
Last active October 24, 2020 21:28
JS Snap a number to an increment
/*
val = value to snap
inc = increment to snap to
example:
snapToIncrement(10, 3): 9
snapToIncrement(89, 10): 100
snapToIncrement(35.6, .5): 35.5
*/
@mattlundstrom
mattlundstrom / functionWithDefaultProperties.js
Last active October 24, 2020 21:30
JS Functions with default properties
var func = function( props ){
props = (typeof props !== "object") ? {} : props;
var mx = props.mx || 10;
var my = props.my || 10;
var mz = props.mz || 10;
var time = props.time || 1;
var delay = props.delay || 0;
var ease = props.ease || Linear.easeNone;
@mattlundstrom
mattlundstrom / rectangle circle collision.js
Last active October 24, 2020 21:29
JS is a rectangle colliding with a circle?
function RectCircleColliding(circle,rect){
var distX = Math.abs(circle.x - rect.x-rect.w/2);
var distY = Math.abs(circle.y - rect.y-rect.h/2);
if (distX > (rect.w/2 + circle.r)) { return false; }
if (distY > (rect.h/2 + circle.r)) { return false; }
if (distX <= (rect.w/2)) { return true; }
if (distY <= (rect.h/2)) { return true; }
@mattlundstrom
mattlundstrom / once_poll.js
Last active October 24, 2020 21:30
JS function that can only be fired once.
// ONCE
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
// FROM http://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with-origin-from-accessing-a-cross-origin-frame
In your main page:
var frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, '*');
In your <iframe> (contained in the main page):
window.addEventListener('message', function(event) {
<body onload=setInterval('for(r.width=j=150,i=j*j;--i;)r.getContext(\'2d\').fillRect(i%j,i/j,1,Math.random())',9)><canvas id=r>
@mattlundstrom
mattlundstrom / gist:9047b969679d5ec8e5de
Created September 16, 2015 19:00
Use Math without "Math"
Object.getOwnPropertyNames(Math).map(function(p) {
window[p] = Math[p];
});
// So instead of Math.random(), just use random();
function randomRange(min, max) {
return min + Math.random() * (max - min);
}
function randomWeightedRange(min, max, expo) {
return toDecimal(((Math.random() * (max - min)) + min), expo);
}
function randomInt(min, max) {
return Math.floor(min + Math.random() * (max - min + 1));
function clamp( value, min, max ){
return Math.min( Math.max( value, min ), max );
}
function randomInt(min,max) {
return Math.floor( min + Math.random() * (max - min + 1) )
}