I want to make the "animation" of my Rect smoother. This is currently really awkward. I know the reason for this. One of the coordinates becomes the required value in front of the other.
For example, if I am in (0,0) and I need to go to (150,75), and I increase every time every second, the y-cord will come much earlier than x-cord.

var canvas = document.getElementById('canvas'); var ctx = document.getElementById('canvas').getContext('2d'); var aniTimer; var x; var y; var tx = tx || 0; var ty = ty || 0; var xDir; var yDir; function followMouse(e) { x = e.offsetX; y = e.offsetY; cancelAnimationFrame(aniTimer); moveObject(); } function moveObject() { ctx.clearRect(0, 0, canvas.width, canvas.height); if (x < tx) { xDir = -1; } else { xDir = 1; } if (y < ty) { yDir = -1; } else { yDir = 1; } tx = tx != x ? tx + xDir : tx; ty = ty != y ? ty + yDir : ty; ctx.fillRect(tx - 25 , ty + 25, 50, 10); if ( tx != x || ty != y ) { aniTimer = window.requestAnimationFrame(moveObject); } } function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; canvas.addEventListener('mousemove', _.throttle(function(e) { followMouse(e); }, 100)); window.addEventListener('resize', resizeCanvas, false); resizeCanvas();
html, body { margin: 0; height: 100%; } canvas { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> <canvas id="canvas"></canvas>
source share