123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container-fluid">
	<canvas id="canvasBouncer" class="center-block" width="600" height="300"><p>Your primitive, sucky browser does not support canvas.</p></canvas>
	<div class="row">
		<div class="col-xs-12 col-sm-6">
			<div class="well">
				<button id="bouncerStart" class="btn" type="submit">Start Bouncing</button>
				<div class="bouncerInput">
					<label>Number of Bouncers</label>
					<input id="bouncerNumber" type="text" placeholder="How many do you want? (1-20)">
					<p id="bouncerErrorNumber" class="bouncerError">Must be a number. Try 1-20</p>
				</div>
				<div class="bouncerInput">
					<label>Starting Angle</label>
					<input id="bouncerAngle" type="text" placeholder="0&deg; is to the right.">
					<p id="bouncerErrorAngle" class="bouncerError">Must be a number. Try 0 - 360</p>
				</div>
			</div>
		</div>
		<div class="col-xs-12 col-sm-6">
			<div class="well well-small">
				<h3>Just a performance tester</h3>
				<p>The button above starts the app by adding some balls and tossing them into the air. Then they bounce around.</p>
				<p>There are default values for the bouncer app, so you don't have to enter anything into these fields. But if you'd like to adjust the bouncers, feel free.</p>
				<p>I've put in a bit of form validation just for kicks, so it won't work if you put letters into one of the fields.</p>
				<p>If you want to get back to my site from here, <a href="http://www.briancribb.com" title="Brian Cribb, Web Developer">just use this link.</a></p>
			</div>
		</div>
	</div>
</div>
            
          
!
            
              .container-fluid {
	max-width: 600px;
}
#bouncerForm {
	padding: 10px 0px 0px 0px;
}
.bouncerError {
	font-size:.8em;
	font-style:italic;
	color:red;
	margin-top:-10px;
	display:none;
}
#bouncerStart {
	margin-bottom:10px;
}
canvas {
	max-width: 100%;
	margin: 15px 15px 20px;
}
            
          
!
            
              //==========================================
$(document).ready(function() {
	/* All site-specific javascript */
	bouncerApp();
});
//==========================================


function canvasSupport() {
	return Modernizr.canvas;
}


function bouncerApp() {
//====================
	//if (!canvasSupport()) {
	//    return;
	//}
	var theCanvas = document.getElementById("canvasBouncer");
	var context = theCanvas.getContext("2d");
	var gravity = .1; // global gravity variable.
	var friction = .9;
	var bouncerArray = new Array();
	
	// For getting the fps
	var timeInterval = 0;
	var lastTime = 0;
	var frame = 0;
	var avgFps = 0;
	
	// Form elements
	var formInputNum = $("#bouncerNumber");
	var formInputAngle = $("#bouncerAngle");
	var inputFields = $(".bouncerInput input");
	
	
	
	// Setting up rAF. Thank you Paul Irish.
	window.requestAnimFrame = (function(){
	  return  window.requestAnimationFrame       || 
			  window.webkitRequestAnimationFrame || 
			  window.mozRequestAnimationFrame    || 
			  window.oRequestAnimationFrame      || 
			  window.msRequestAnimationFrame     || 
			  function( callback ){
				window.setTimeout(callback, 1000 / 60);
			  };
	})();


	// Initial function calls.
	$("#bouncerStart, #canvasBouncer").click(function() {
		$(".bouncerError").hide();
		removeBouncers();
		checkInputs();
	});    
	animloop(); // Kicking off the RaF. It will self-call after this.


// ====================
// FUNCTIONS
// ====================


	function animloop(){
	  requestAnimFrame(animloop);
	  drawCanvas();
	}


	function drawCanvas() {
		// Clear Canvas. Or in this case, add a gradient.
		var gr = context.createLinearGradient(0, theCanvas.height, 0, 0);
		gr.addColorStop(0 , '#F5F5F5');
		gr.addColorStop(.5, '#e4e4e4');
		gr.addColorStop(1,  '#e1e1e1');
		context.fillStyle = gr;
		//context.fillRect(0, 0, 100, 100);   
		//context.fillStyle = "#dddddd";
		context.fillRect(0,0,theCanvas.width,theCanvas.height);
		renderBouncers();
		
		//Line
		context.strokeStyle = '#cdcdcd'
		context.lineWidth = 2;
		context.lineCap = 'square';
		context.beginPath();
		context.moveTo(0,0);
		context.lineTo(theCanvas.width, 0);
		context.lineTo(theCanvas.width,theCanvas.height);
		context.lineTo(0,theCanvas.height);
		context.lineTo(0,0);
		context.stroke();
		context.closePath();
		
		//Text
		context.fillStyle = "#000000";
		context.font = "24px Arial";
		context.textBaseline = "top";
		context.textAlign="left";
		context.fillText ("BouncerApp", 10, 10);
		context.font = "16px Arial";
		context.fillText ("(click on Something.)", 10, 40);
		
		
		//context.fillText("fps: " + this.controller.avgFps.toFixed(1), this.canvas.width - 93, 22);
		//getfps();
		context.textAlign="right";
		context.fillText("fps: " + getfps(), theCanvas.width - 10, 10);
		
	}// end of drawCanvas()
	
	
	function checkInputs() {
		var ready = true;
		inputFields.each(function(index) {            
			var tempCheck = $(this).val() - 0;
			if (isNaN(tempCheck)) {
				$(this).next(".bouncerError").show();
				ready = false;
			}
		});
		ready === true && initBouncers(); // If ready is true, go ahead,
	}
	
	function initBouncers() {
		var inputNum = formInputNum.val();
		var inputAngle = formInputAngle.val();
		
		var bouncerNum = inputNum > 0 ? inputNum : 15;
		
		
		
		for (i = 0; i< bouncerNum; i++) {
			// Randomly placed, but no less than 30 pixels from each side.
			var tempX = 40 + ( Math.floor( Math.random() * (theCanvas.width - 70) ) );
			var tempY = 40 + ( Math.floor( Math.random() * (theCanvas.height - 70) ) );
			// Larger objects will go slower.
			var tempRadius = 10 + ( Math.floor( Math.random() * 10 ) );
			var tempSpeed =  15 - ((tempRadius / 2) + 1);
			var tempElasticity = .75 - ((tempRadius) * .01 );
			//Checking for user input.
			if(inputAngle) {
				var tempAngle = (inputAngle - 30) + ( Math.floor( Math.random() * 60 ) );
			}
			else {
				var tempAngle = ( Math.floor( Math.random() * 360 ) );
				//alert('hi');
			}
			
			// New Bouncer instance.
			var bouncerTemp = new Bouncer( { x:tempX, y:tempY, radius:tempRadius, angle:tempAngle, speed:tempSpeed, elasticity:tempElasticity  } );
			bouncerArray.push(bouncerTemp);
		}
	}
	function renderBouncers() {
		//var bouncer1 = new bouncer();
		for (i = 0; i< bouncerArray.length; i++) {
			bouncerArray[i].drawSelf();
		}
	}
	function removeBouncers() {
		//var bouncer1 = new Bouncer();
		//for (i = 0; i< bouncerArray.length; i++) {
		//    bouncerArray[i].removeSelf();
		//}
		bouncerArray.length = 0;
	}
	
	
	function getfps() {	   
		frame ++; 
		var date = new Date();
		var thisTime = date.getTime();
		timeInterval = 1000 / (thisTime - lastTime);
		lastTime = thisTime;
		//console.log('thisTime = ' + Math.round(thisTime) + ', lastTime = ' + Math.round(lastTime) + ', timeInterval = ' + Math.round(timeInterval));
		
		if (frame % 10 == 0) {
			avgFps = Math.round(timeInterval * 10) / 10;
			
		}
		//console.log('avgFps = ' + avgFps );
		return avgFps.toFixed(0);
	};    
	
	
	
	
	
	
		
	// ===========================================================
	function Bouncer(settings) { // Bouncer Class
		var defaults = { x:30, y:30, radius:10, angle:45, speed:2, elasticity:.7 }
		var option = $.extend(defaults, settings);
		var radians = option.angle * Math.PI/ 180;

		this.x = option.x;
		this.y = option.y;
		this.radius = option.radius;
		this.velocityx = Math.cos(radians) * option.speed;
		this.velocityy = Math.sin(radians) * option.speed;
		this.elasticity = option.elasticity;
		
		
		
		Bouncer.prototype.drawSelf = function () {
			this.updatePosition();

			// draw the Bouncer in its new position.
			context.fillStyle = "#000000";
			context.beginPath();
			context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
			context.closePath();
			context.fill();
		}
		
		Bouncer.prototype.updatePosition = function () {
			this.velocityy += gravity;
			this.x += this.velocityx;
			this.y += this.velocityy;
			
			
			// Preparing velocities for the next frame.
			//=========================================
			// bouncing off the left wall.
			if ( (this.x - this.radius) < 0 ) {
				this.x = this.radius;
				this.velocityx = -(this.velocityx) * this.elasticity;
			}
			//  bouncing off the right wall.
			if ( (this.x + this.radius) > theCanvas.width) {
				this.x = theCanvas.width - this.radius;
				this.velocityx = -(this.velocityx) * this.elasticity;
			}
			// bouncing off the ceiling.
			if ( (this.y - this.radius) < 0 ) {
				this.y = this.radius;
				this.velocityy = -(this.velocityy);
				
			}
			// bouncing off the floor.
			if ( (this.y + this.radius) >= theCanvas.height) {
				this.y = theCanvas.height - this.radius;
				this.velocityy = -(this.velocityy) * this.elasticity;
				this.velocityx *= friction;
				if ( Math.abs(this.velocityy) <= .1 ) {
					this.velocityy = 0;
				}
				if ( Math.abs(this.velocityx) <= .02 ) {
					this.velocityx = 0;
				}
			}
			
			//if (this.velocityx == 0 && this.velocityy == 0) {
			//    this.removeSelf();
			//}
		}
		
		// Remove self from main array, now ready for garbage collection.
		Bouncer.prototype.removeSelf = function () {
			var thisIndex = jQuery.inArray( this, bouncerArray );
			bouncerArray.splice( thisIndex,1 );
		}

	} //end of Bouncer class
	// ===========================================================
	
}// end of bouncerApp()
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console