Так что я начинающий и решил немного научиться работать с canvas.Я следовал за некоторыми уроками и сумел сделать «шар», чтобы следовать за моей мышью.И это работает.Однако есть задержка.Когда я двигаю мышью, «шарики» следуют за моей мышью, но с задержкой.Всегда немного поздно.Итак, мой вопрос ... Это то, как это должно быть (то, как работает холст, и нет пути его обойти) m или я делаю что-то не так.
Вот мой код JavaScript:
let canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
let mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};
addEventListener('mousemove', function (event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
})
function Ball(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.update = function() {
// eventualy some other code here...
this.draw();
};
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.closePath();
};
};
let ball;
function init() {
ball = new Ball(mouse.x, mouse.y, 30, 'red');
};
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
ball.x = mouse.x;
ball.y = mouse.y;
ball.update();
};
init();
animate();
Мой HTML:
<body>
<canvas></canvas>
<script src="javascript.js"></script>
</body>
let canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
let mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};
addEventListener('mousemove', function(event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
})
function Ball(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.update = function() {
// eventualy some other code here...
this.draw();
};
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.closePath();
};
};
let ball;
function init() {
ball = new Ball(mouse.x, mouse.y, 30, 'red');
};
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
ball.x = mouse.x;
ball.y = mouse.y;
ball.update();
};
init();
animate();
<canvas></canvas>
Любая помощь будет принята с благодарностью.
PS Обновлено по запросу.Это весь мой код.