title: Only clean partial drawings on the canvas
body: <p>I see you can clear part of the canvas using <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect" rel="nofollow noreferrer">CanvasRenderingContext2D.clearRect</a>. This function will clear up full/partial canvas based on the coordinates specified. Is it possible to clear some of the foreground drawings, but keep the background drawings intact? </p>
  
  <p>Inside of react component, I have the following</p>
  
  <pre class="lang-js prettyprint-override"><code>  componentDidMount() {
      this.canvas = this.canvasRef.current;
      this.c = this.canvas.getContext('2d')
  
      this.canvas.width = window.innerWidth
      this.canvas.height = window.innerHeight
  
      window.addEventListener('resize', this.resize)
  
      this.init() 
      this.backgroundGradientAnimate() //draw background gradient
      window.requestAnimationFrame(this.step)
  
    }
  
    // generate stars
    init = () =&gt; {
      this.stars = []
  
      for (let i = 0; i &lt; 150; i++) {
        const x = Math.random() * this.canvas.width;
        const y = Math.random() * this.canvas.height
        const r = Math.random() * 3
        this.stars.push(new Star(x, y, r, 'white'))
      }
    }
  
    draw = (star) =&gt; {
      this.c.save()
      this.c.beginPath()
      this.c.arc(star.x, star.y, star.radius, 0, Math.PI * 2, false)
      this.c.fillStyle = this.getRandomColor()
      this.c.fill();
      this.c.closePath();
      this.c.restore()
    }
  
    starsAnmiate = () =&gt; {
      this.stars.forEach(star =&gt; this.draw(star))
    }
  
    // only animate in such time
    step = (elapsedTime) =&gt; {
      let delta = elapsedTime - this.lastFrameTime || 0
  
      window.requestAnimationFrame(this.step)
  
    if (this.lastFrameTime &amp;&amp; delta &lt; 1000) {
      return;
    }
  
    this.lastFrameTime = elapsedTime
  
    this.starsAnmiate();
    }
  </code></pre>
  
  <p>The issue is that all the stars never cleared out after animations repeat itself. Is there way of only cleaning up the drawing of stars but retaining the <code>backgroundGradient</code>, or two drawings always have to be cleaned at the same time because they sit on the same canvas? </p>
  
  <p>Overall, I'm trying to create a blinking effect of those stars. It just seems to be lots of overhead when I need to clean/redraw the entire canvas every time to simulate the blinking of each star.</p>
  
  <p>[EDIT]</p>
  
  <ol>
  <li>To optimize animation effort, you can draw 2 separate canvas as <a href="https://stackoverflow.com/questions/3008635/html5-canvas-element-multiple-layers">HERE</a></li>
  </ol>