So I am kinda beginner here and decided to try and learn working with canvas a little bit. I followed some tutorials and managed to make a 'ball' to follow my mouse. And it works. However there is a delay. When i move my mouse the 'balls' follows my mouse but with delay. It is always late a little bit. So my question is... Is this is how it is supposed to be (that how canvas work and there is no way around it)m or I am doing something wrong.
Here is my javascript code:
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();
My 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>
Any help would be greatly appreciated.
P.S. Updated as requested. This is my entire code.