0

what I think the problem I am having is that when animating, the canvas is not clearing when the radius of the circle is decreasing.

The ironical part is that it works perfectly when the radius of the circle is increasing and I can see the circle is growing big on canvas but it stops animating when it starts decreasing. I did console.log and technically the numbers are decreasing fine but I can not see it animated

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight


let radius = 50
let dx = 5
function animate(){
  c.clearRect(0, 0, canvas.width, canvas.height)
  c.fillStyle = "pink"
  c.arc(canvas.width/2, canvas.height/2, radius, 0, Math.PI * 2, 
  true)
  c.fill()
  radius += dx

if( radius * 2 > canvas.width || radius * 2 < 10) {
  dx = -dx
 }

  requestAnimationFrame(animate)
}
animate()
cyo21
  • 31
  • 1
  • 6

2 Answers2

0

Irony is when do something to avoid something else from happening, only to make what you were trying to avoid, happen.

So with language out of the way: you forgot c.beginPath() - that arc instruction is a pathing instruction, so right now you're simply adding more and more and more arcs to the same path, and fill() then fills all of them, which means that you'll see an area the size of "the biggest arc in that collection" coloured pink.

Adding an explicit beginPath will make the canvas throw away any old paths and only colour the currently active path:

    const canvas = document.querySelector('canvas')
    const w = canvas.width = 200
    const h = canvas.height = 200

    const c = canvas.getContext('2d')
    c.fillStyle = "pink"

    let radius = 50
    let dx = 1

    function animate(){
        c.clearRect(0, 0, w, h)

        c.beginPath()
        c.arc(w/2, h/2, radius, 0, Math.PI * 2, true)
        c.fill()
        
        radius += dx

        if( radius > w/2 || radius < 10) {
            dx = -dx
        }

        requestAnimationFrame(animate)
    }

    animate()
<canvas></canvas>
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
0

You should call beginPath() every time you want to start a new path - that is a new circle.

When your circle is so big, the smaller inner circles are also drawn from top down the larger ones - so, they are not visible.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// First path
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();

// Second path
ctx.beginPath();
ctx.strokeStyle = 'green';
ctx.moveTo(20, 20);
ctx.lineTo(120, 120);
ctx.stroke();
Charlie
  • 22,886
  • 11
  • 59
  • 90