Hello, I ask for help in the following: It is necessary to make an animation so that in a given area (square), an object (circle) will arbitrarily bounce off the mouse cursor, without flying out of the specified area.
<html> <head> <title>Тени и простенькая анимация</title> <script type="text/javascript"> var canvas, ctx, w, h; var ball = { x : 50, y : 100, r : 15, vx : 0, vy : 0 }; var count = 0; function init() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); w = canvas.width; h = canvas.height; ctx.font = "18px Times-Roman"; ctx.strokeRect(0, 0, w, h); } setInterval(function() { ctx.clearRect(1, 1, w - 2, h - 2); ball.x += ball.vx; ball.y += ball.vy; ball.vx *=1; ball.vy *= 1; ball.vy += .55; if (ball.y + ball.r > h - 15) { count++; ball.y = h - 15 - ball.r; ball.vy = -Math.abs(ball.vy); } if (count >= 1) { ball.vy *= 0.99; } if (count == 1) { ball.vx =5; } if (ball.x+ball.r > w - 15) { ball.x = w - 30; ball.vx = -Math.abs(ball.vx); } if (ball.x < 30) { ball.x = 30; ball.vx = -ball.vx; } ctx.save(); ctx.fillText("Count: " + count, 250, 50); ctx.fillStyle = "black"; ctx.translate(ball.x, ball.y); ctx.beginPath(); ctx.arc(0, 0, ball.r * 2, 0, 2 * Math.PI, true); ctx.closePath(); ctx.fill(); ctx.restore(); },25); </script> </head> <body onload="init()"> <canvas id="canvas" width="600" height="600"> error </canvas> </body> </html>