'move balls in canvas
i'm trying to make my balls move in this canvas but every time i got something else i got creating a new balls like i'm refreshing the page so can any one tell me how to move this balls
var windowElenemt = document.getElementById("window");
var ctx = windowElenemt.getContext('2d');
var vx = 9;
var vy = 9;
function draw(){
var ballsColors = Math.floor(Math.random()*16777215).toString(16);
var boxY = Math.floor(Math.random()*600);
var boxX = Math.floor(Math.random()*1360);
var ballPlace = Math.floor((Math.random()*30)+5);
ctx.clearRect(0,0,windowElenemt.width,windowElenemt.height);
boxX+=vx;
boxY+=vy;
ctx.beginPath();
ctx.arc(boxX,boxY,ballPlace,0,2*Math.PI,false);
ctx.fillStyle = "#" + ballsColors;
ctx.fill();
requestAnimationFrame(draw);
}
setInterval(draw(),1000);
for(i = 0 ; i < 20 ; i++){
draw();
}
<body onload="draw()">
<canvas id="window" width= '1364' height='623' style="border:1px solid #d3d3d3;" display:'block;'></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="index.js" charset="utf-8"></script>
</body>
Solution 1:[1]
it seems like your boxX and boxY variables are declared to have a random number. i see you call the draw() function multiple times. i think its probably that each time your draw() function executes it re-declares the boxX and boxY values. try declaring them outside the draw() function like this
var windowElenemt = document.getElementById("window");
var ctx = windowElenemt.getContext('2d');
var vx = 0.1;
var vy = 0.1;
var boxY = Math.floor(Math.random()*600);
var boxX = Math.floor(Math.random()*1360);
var ballPlace = Math.floor((Math.random()*30)+5);
//var ballsColors = Math.floor(Math.random()*16777215).toString(16);
function draw(){
boxX+=vx;
boxY+=vy;
ctx.clearRect(0,0,windowElenemt.width,windowElenemt.height);
ctx.beginPath();
ctx.arc(boxX,boxY,ballPlace,0,2*Math.PI,false);
ctx.fillStyle = "#000000";
ctx.fill();
requestAnimationFrame(draw);
}
setInterval(draw(),1000);
for(i = 0 ; i < 20 ; i++){
draw();
}
i changed the vx and vy to 0.1 because it would leave the screen too fast and you wont be able to see it. if you turn off the ctx.clearrect part you can see exactly how it moved because it wont be clearing it anymore.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | octoCat |
