Javascript - drawRect is interfering with the background color

1

When I put a square on canvas the background goes white.

(function(){
  var c = document.createElement("canvas");
  var ctx = c.getContext('2d');
  var fps = 30;
  var height = 300;
  var width = 300;
  var Bloco = new bloco();
  c.width = 300;
  c.height = 300;
  document.body.appendChild(c)

  setInterval(draw(), 1000/fps)

  function draw(){
    background("black");

    Bloco.put();

  }
  function bloco(x, y, size, color){
    this.size = size;
    this.x = x;
    this.y = y;
    this.color = color;

    this.put = function(){
      quadrado(10, 10, 10, "white");
    }
  }
  function quadrado(x, y, size, color){
    ctx.rect(x, y, size+x, size+y);
    ctx.fillStyle = color;
    ctx.fill();
  }
  function background(color){
    ctx.rect(0, 0, width, height);
    ctx.fillStyle = color;
    ctx.fill();
  }
})();
<body>
  <script src="javascript.js" type="text/javascript"></script>
<body>

I wanted to know how to draw a square without breaking the color of the background !

    
asked by anonymous 16.05.2018 / 00:32

1 answer

1

Before starting each drawing / path, you must call the beginPath () to "empty" the path list, otherwise the fill command will populate the canvas with the previous path ( background ) .

The code looks like this:

function quadrado(x, y, size, color){
    ctx.beginPath(); // AQUI: Colocar o beginPath()
    ctx.rect(x, y, size+x, size+y);
    ctx.fillStyle = color;
    ctx.fill();
}

function background(color){
    ctx.beginPath(); // AQUI: Colocar o beginPath()
    ctx.rect(0, 0, width, height);
    ctx.fillStyle = color;
    ctx.fill();
}

See it working: Here

    
16.05.2018 / 22:44