Bouncing ball
by flakas
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r57/three.min.js"></script>
<canvas id="container" width="400" height="300"></canvas>
<div class="ball-stats">
<div>PosX <span id="posx">0</span></div>
<div>PosY <span id="posy">0</span></div>
<div>SpeedX <span id="speedx">0</span></div>
<div>SpeedY <span id="speedy">0</span></div>
<div>Size <span id="ballsize">0</span></div>
</div>
CSS
canvas {
border: 1px solid #000;
}
.ball-stats {
float: right;
width: 300px;
}
JavaScript
/*global $:false, document:false, THREE:false, window:false */
window.requestAnimFrame = (function () {
"use strict";
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 10);
};
}());
$(document).ready(function () {
"use strict";
var posX = $('#posx'),
posY = $('#posy'),
speedX = $('#speedx'),
speedY = $('#speedy'),
ballsize = $('#ballsize');
function Ball(size, position, speed, canvas) {
this.size = size;
this.position = position;
this.speed = speed;
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.color = {r: 0, g: 0, b: 0};
this.draw = function () {
// Leave trails
this.ctx.fillStyle = "rgba(255, 255, 255, 0.2)";
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// Draw the ball
this.ctx.fillStyle = "rgb(" + this.color.r + ", " + this.color.g + ", " + this.color.b + ")";
this.ctx.beginPath();
this.ctx.arc(this.position.x, this.position.y, this.size, 0, Math.PI * 2, false);
this.ctx.fill();
};
this.changeColor = function () {
this.color.r = Math.round(Math.random() * 255);
this.color.g = Math.round(Math.random() * 255);
this.color.b = Math.round(Math.random() * 255);
};
var MAX_SPEED = 20;
this.step = function () {
// Keep the ball within the frame
this.position.x += this.speed.x;
if (this.position.x + this.size > this.canvas.width) {
this.position.x = this.canvas.width - this.size;
}
if (this.position.x < this.size) {
this.position.x = this.size;
}
this.position.y +=...