Надеюсь, это поможет. сложная часть делает убедительную «остановку».
function getCoordinates(event) { return { x: event.offsetX, y: event.offsetY }; }
function spawnBall(coords, x, y, dx, dy){
x.push(coords.x);
y.push(coords.y);
dx.push(0);
dy.push(2);
}
// =========================
// Draws the various entities
// =========================
function draw(canvas, image, x, y, width, height) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < x.length; i++){ context.drawImage(image, x[i], y[i], width, height); }
}
// =========================
// =========================
// At the moment all this is concerned with is the "floor"
// =========================
function move(x, y, dx, dy, gravity, bounciness, floor){
for(var i = 0; i < x.length; i++){
// =========================
// Ball is close to the floor and not moving very fast, set it to rest
// otherwise it bounces forever.
// =========================
if (y[i] >= floor - 10 && Math.abs(dy[i]) <= 2 * gravity) {
dy[i] = 0;
y[i] = floor;
continue;
}
// =========================
// =========================
// Update the speed and position
// =========================
dy[i] += gravity;
y[i] += dy[i];
// =========================
// =========================
// Simulate a bounce if we "hit" the floor
// =========================
if(y[i] > floor) {
y[i] = floor - (y[i] - floor);
dy[i] = -1.0 * bounciness * dy[i];
}
// =========================
}
}
// =========================
document.addEventListener("DOMContentLoaded", function(event){
var canvas = document.getElementById("bouncingField");
canvas.width = window.innerWidth - 50;
canvas.height = window.innerHeight - 50;
//Image to use as ball texture
var image = new Image();
image.src = "http://www.freeiconspng.com/uploads/soccer-ball-icon-14.png";
var gravity = 1;
var ballSize = 50;
var ballBounciness = 0.8;
var floor = canvas.height - ballSize;
var x = [];
var y = [];
var dx = [];
var dy = [];
// =========================
// This can be done via requestAnimationFrame()
// https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
// =========================
var isSpawned = false;
setInterval(function(){
if(!isSpawned){ return; }
move(x, y, dx, dy, gravity, ballBounciness, floor)
draw(canvas, image, x, y, ballSize, ballSize);
}, 10);
// =========================
// =========================
// Add a ball
// =========================
canvas.onclick = function(event) {
isSpawned = true;
var coords = getCoordinates(event);
spawnBall(coords, x, y, dx, dy);
}
// =========================
});
body {
background-color: #555555;
}
#bouncingField {
border-style: solid;
border-width: 10px;
border-color: white;
}
<canvas id="bouncingField"></canvas>