簡體   English   中英

畫布動畫要轉到鼠標坐標

[英]Canvas Animation To Go To Mouse Coords

如何為類似於特定游戲http://www.agar.io的特定坐標對的圓設置動畫? 我已經嘗試過jQuery animate()函數,但是由於我希望圓移動到的坐標不斷更新,因此它的運行速度很慢。

agar.io僅使用核心畫布功能。

這是一個顯示光標跟隨球的示例。

 canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); ctx.canvas.width = 500; ctx.canvas.height = 500; var V2 = function(x, y) { this.x = x; this.y = y; }; var cursor = new V2(0, 0); var ballSize = 20; var ball = new V2(0, 0); ctx.DrawGrid = function(size) { this.fillStyle = "black"; for (var x = 0; x != 25; x++) for (var y = 0; y != 25; y++) this.strokeRect(x * size, y * size, size, size); } var main = setInterval(function() { ctx.clearRect(0, 0, 5000, 5000); if (cursor.x > ball.x - ballSize) ball.x += 3; if (cursor.y > ball.y - ballSize) ball.y += 3; if (cursor.x < ball.x + ballSize) ball.x -= 3; if (cursor.y < ball.y + ballSize) ball.y -= 3; if (ball.x < ballSize) ball.x = ballSize; if (ball.y < ballSize) ball.y = ballSize; if (ball.x > ctx.canvas.width - ballSize) ball.x = ctx.canvas.width - ballSize; if (ball.y > ctx.canvas.height - ballSize) ball.y = ctx.canvas.height - ballSize; ctx.DrawGrid(50); ctx.beginPath(); ctx.arc(ball.x, ball.y, ballSize, 0, 2 * Math.PI); ctx.fill(); }, 33); document.onmousemove = function(e) { cursor.x = e.pageX; cursor.y = e.pageY; } 
 html, body { margin: 0px; } 
 <canvas id="canvas"></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM