The question says it all. I'm just trying to make this function work to make something work. How do I log the position of x and y continuously? I have tried making a function for it, and also putting that function in a for loop.
Maybe I'm just too newbie to understand what I'm doing. Which is why I'm asking you good fellows!
here is my javascript. Dont think you need the html because this is all in the canvas tag.
const body = document.body;
let canvas = document.querySelector('#myCanvas');
let c = canvas.getContext('2d');
body.style.overflowX = 'hidden';
canvas.width = window.innerWidth;
canvas.height = 500;
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
let dx = 15;
let dy = Math.random();
let xwidth = 10;
let yheight = 10;
function animatedSquare() {
requestAnimationFrame(animatedSquare);
c.clearRect(0,0,canvas.width, canvas.height);
c.fillRect(x,y,xwidth,yheight);
if(x > canvas.width || x - xwidth < 0) {
dx = -dx;
}
if(y > canvas.height ||y - yheight < 0) {
dy = -dy;
}
x += dx;
y += dy;
}
animatedSquare();
console.log(x,y);
I think using setInterval should solve you issue. Just log like this setInterval(functionName(arg1,arg2....), 1000); here
1000 is millisecond so it means 1second you can change it to you need. It will run until you use a clearInterval in your code
You could call an async function instead of a normal function
Example:
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
Async function documentation:
https://sodocumentation.net/javascript/topic/925/async-functions--async-await
If you don't want to run a daemon function for this, You should use the onmousemove() event
Simply add a <div> tag parent to the #myCanvas id with onmousemove() calling a function:
<div onmousemove="myFunction()">Move the cursor over me</div>
Sample code for myFunction() would be:
myFunction() => {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
console.log(x,y);
}
onmousemove() Documentation:
https://www.w3schools.com/jsref/event_onmousemove.asp
If I am interpreting your question correctly, you just need to put your last line of code, i.e., console.log(x, y), inside your animatedSquare() function, e.g.;
function animatedSquare() {
requestAnimationFrame(animatedSquare);
c.clearRect(0,0,canvas.width, canvas.height);
c.fillRect(x,y,xwidth,yheight);
if(x > canvas.width || x - xwidth < 0) {
dx = -dx;
}
if(y > canvas.height ||y - yheight < 0) {
dy = -dy;
}
x += dx;
y += dy;
console.log(x,y);
}