JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id = "canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx=canvas.getContext("2d");
height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.height = height;
playerY = height / 2;
playerX = 50;
var circle = new Image();
circle.src = "https://s21.postimg.org/4zigxdh7r/circ.png";
ctx.drawImage(circle, playerX, playerY);
move();
function move(){
velocity = height * 0.00050; // the velocity should be proptional to screen height.
startPos = playerY,
endPos = 0,
distanceY = endPos - playerY,
startTime = Date.now(),
duration = Math.abs(distanceY) / velocity;
requestAnimationFrame(startMoving);
function startMoving(){
var elapsedTime = Math.min(Date.now() - startTime, duration), cbEnd = false;
if (elapsedTime < duration){
setTimeout(function() {
requestAnimationFrame(startMoving);
// Drawing code goes here
}, 1000 / 60);
}
else cbEnd = true;
playerY = startPos - (elapsedTime * velocity);
console.log(playerY);
ctx.clearRect(0, 0, window.innerWidth, height);
ctx.drawImage(circle, playerX, playerY); //drawing circle
if(cbEnd) console.log("over");
}
}