1

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>
Drew
  • 23
  • 7

1 Answers1

1

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>
Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • 1
    And to bouce it left to right do something like this http://jsfiddle.net/c4vxb9tx/ (based on the answer, you can replace vectorx with the speed if you want) – dwana Nov 03 '14 at 15:15
  • And dwana , i have a question. Is it possible to use a parameter in your code? I want to learn more how to put a parameter in my code :) – Drew Nov 03 '14 at 15:57