Drew
Drew

Reputation: 23

Moving circle in a straight line from left to the right of canvas

I am here trying to draw a moving circle in a straight line with this code. But im wrong to put a syntax. Help me to correct this code.

<script>

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

function draw_circle (circleX, circleY, radius, fill) { 
    context.fillStyle = "black";
    context.fillRect(0, 0, 800, 300);

    context.strokeStyle = "red";
    context.strokeRect(5, 5, 790, 290);

    var speed = 5

    context.fillStyle = fill;
    context.arc(circleX, circleY, radius, 0, Math.PI*2);
    context.fill();
}

setInterval(draw_circle(100,100, 30 , "cyan"), 33);

</script>

Upvotes: 1

Views: 2479

Answers (1)

Kaiido
Kaiido

Reputation: 137171

You will have to clear your canvas (using canvas.width = canvas.width or clearRect())

Note that you will have to add context.beginPath() in order to have clearRect() do his job.

Once done you just have to increment the x position of your arc.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

function draw_circle (circleX, circleY, radius, fill) { 
    //clear the canvas
    context.clearRect(0,0,canvas.width, canvas.height);

    context.beginPath();
    context.fillStyle = "black";
    context.fillRect(0, 0, 800, 300);

    context.strokeStyle = "red";
    context.strokeRect(5, 5, 790, 290);
    var speed = 5;
    //just a loop if you don't want it simply use `i+=speed;`
    (i>canvas.width+radius)?i=(radius*-2):i+=speed;
    context.fillStyle = fill;
    context.arc(circleX, circleY, radius, 0, Math.PI*2);
    context.fill();
}

var i=0;

setInterval(function(){draw_circle(i,100, 30 , "cyan")}, 33);
<canvas id = "myCanvas"></canvas>

Upvotes: 1

Related Questions