html - Make canvas element orbit around/follow mouse -
i want cyan dot spin around in canvas chasing mouse, mouse has gravity. think of mouse planet , object comet. tried code, makes cyan dot spin crazy , not follow mouse much.
<div class="section"> <div id="intro"> <div id="mouse" style="border-radius: 50%; position: absolute;height: 20px;width: 20px;background-color: blue;"></div> <canvas id="canvas" style="background:black;"> </canvas> <script> var canvas = document.getelementbyid("canvas"); canvas.width = $(window).width(); canvas.height = $(window).height(); </script> <script> var canvas = document.queryselector("#canvas") var ctx = canvas.getcontext("2d"); var mousex; var mousey; var kule = { cx : 100, cy : 100, vy : 2, vx : 2, r : 5, e : 1, color : "cyan" }; function draw() { var image = new image(); image.src = "player.png"; ctx.drawimage(image, 100, 100); var boundsx = canvas.width; var boundsy = canvas.height; //ctx.clearrect(0, 0, bounds, bounds); ctx.fillstyle = kule.color; ctx.beginpath(); ctx.arc(kule.cx, kule.cy, kule.r, 0, math.pi * 2); ctx.fill(); ctx.closepath(); var deltax = mousex - kule.cx; var deltay = mousey - kule.cy; kule.vy = kule.vy + deltax/1000; kule.vx = kule.vx + deltay/1000; kule.cx = kule.cx + kule.vx; kule.cy = kule.cy + kule.vy; if (kule.cy + kule.r >= boundsy) { kule.vy = -kule.vy * kule.e; kule.vy = -(math.abs(kule.vy)) * kule.e; } if (kule.cx + kule.r >= boundsx) { kule.vx = -kule.vx * kule.e; kule.vx = -(math.abs(kule.vx)) * kule.e; } if (kule.cy - kule.r <= 0) { kule.vy = kule.vy * kule.e; kule.vy = (math.abs(kule.vy)) * kule.e; } if (kule.cx - kule.r <= 0) { kule.vx = kule.vx * kule.e; kule.vx = (math.abs(kule.vx)) * kule.e; } } setinterval(draw, 10); $(document).on("mousemove",function(event){ mousex = event.pagex; mousey = event.pagey; $("#mouse").animate( { left:mousex-10, top:mousey-10 },0)}); </script> </div>
i removed pieces of code simplify answer, here's idea :
var starttime = (new date()).gettime(); var rotationspeed = 500; // milliseconds full turn var orbitradius = 75; function draw() { var boundsx = canvas.width; var boundsy = canvas.height; ctx.clearrect(0, 0, boundsx, boundsy); ctx.fillstyle = kule.color; var currenttime = (new date()).gettime(); var passedtime = currenttime - starttime; var angle = math.pi * 2 * (passedtime / rotationspeed); ctx.beginpath(); ctx.arc(mousex + math.cos(angle) * orbitradius, mousey + math.sin(angle) * orbitradius, kule.r, 0, math.pi * 2); ctx.fill(); }
Comments
Post a Comment