gpt4 book ai didi

javascript - 用于转到鼠标坐标的 Canvas 动画

转载 作者:行者123 更新时间:2023-12-03 09:27:30 24 4
gpt4 key购买 nike

如何制作一个指向特定坐标对的圆圈动画,类似于游戏 http://www.agar.io ?我已经尝试过 jquery animate() 函数,但它慢得要命,因为我希望圆圈移动到的坐标不断更新。

最佳答案

agar.io 仅使用核心 Canvas 功能。

这是一个显示球跟随光标移动的示例。

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>

关于javascript - 用于转到鼠标坐标的 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com