1

Something is wrong with my canvas coding. It is not working properly. The shift() works only once. It should make the drawing disappear, but it is working normal purpose. Did I do something wrong?

<canvas id='ctx' width="500px" height="500px" style="border:1px solid red;"></canvas>
<script type="text/javascript">
//object array
car_asd=[
  {x:100,y:100},
  {x:105,y:100},
  {x:110,y:100}
];
// end of object array
var ctx=document.getElementById("ctx").getContext("2d"); 
function a() {
  car_asd.shift();//does not working all time
  for(i=0;i<3;i++){
    cars=car_asd[i];
    ctx.fillRect(cars.x,cars.y,10,10);
  }
}
setInterval(function(){ a() }, 10);
</script>>

1 Answer 1

1

There's nothing wrong with the shift(), the problem is that the drawings from previous calls to a() is still showing.

So, you need to clear the canvas at the beginning of the function a():

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.