I am trying to create one website for monitoring kind of thing. Here i need to control the speed of the ball. How to do that? Then i need to change the color of the balls to red if it collide or overlay with other. If not, it should remain green . I have no idea how to do these thing. Can anyone please help with this?
function getBall(xVal, yVal, dxVal, dyVal, rVal, colorVal) {
var ball = {
x: xVal,
lastX: xVal,
y: yVal,
lastY: yVal,
dx: dxVal,
dy: dyVal,
r: rVal,
color: colorVal,
normX: 0,
normY: 0,
durationAverage: 0,
durationMin: Number.MAX_SAFE_INTEGER,
durationMax: 0,
bounceCount: 0
};
return ball;
}
var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext("2d");
var containerR = 200;
canvas.width = containerR * 2;
canvas.height = containerR * 2;
canvas.style["border-radius"] = containerR + "px";
var balls = [
getBall(canvas.width / 2, canvas.height - 30, 2, -2, 8, "#32CD32"),
getBall(canvas.width / 3, canvas.height - 50, 3, -3, 8, "#32CD32"),
getBall(canvas.width / 4, canvas.height - 60, -3, 4, 8, "#32CD32"),
getBall(canvas.width / 2, canvas.height / 5, -1.5, 3, 8, "#32CD32")
];
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < balls.length; i++) {
var curBall = balls[i];
ctx.beginPath();
ctx.arc(curBall.x, curBall.y, curBall.r, 0, Math.PI * 2, false);
ctx.fillStyle = curBall.color;
ctx.fill();
ctx.closePath();
curBall.lastX = curBall.x;
curBall.lastY = curBall.y;
curBall.x += curBall.dx;
curBall.y += curBall.dy;
var dx = curBall.x - containerR;
var dy = curBall.y - containerR;
if (Math.sqrt(dx * dx + dy * dy) >= containerR - curBall.r) {
var start = performance.now();
// current speed
var v = Math.sqrt(curBall.dx * curBall.dx + curBall.dy * curBall.dy);
// Angle from center of large circle to center of small circle,
// which is the same as angle from center of large cercle
// to the collision point
var angleToCollisionPoint = Math.atan2(-dy, dx);
// Angle of the current movement
var oldAngle = Math.atan2(-curBall.dy, curBall.dx);
// New angle
var newAngle = 2 * angleToCollisionPoint - oldAngle;
// new x/y speeds, using current speed and new angle
curBall.dx = -v * Math.cos(newAngle);
curBall.dy = v * Math.sin(newAngle);
var end = performance.now();
var curDuration = end - start;
curBall.bounceCount++;
curBall.durationAverage = (((curBall.bounceCount - 1) * curBall.durationAverage) + curDuration) / curBall.bounceCount;
if (curDuration < curBall.durationMin) {
curBall.durationMin = curDuration
}
if (curDuration > curBall.durationMax) {
curBall.durationMax = curDuration
}
}
}
requestAnimationFrame(draw);
}
draw();
canvas {
background: #eee;
}
<canvas id="Canvas"></canvas>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>