Javascript - drawRect is interfering with the background color

Asked

Viewed 61 times

1

When I put one squared in canvas the bottom turns 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 squared without interfering in the color of bottom!

1 answer

1


Before starting each drawing/path, it is necessary to call the method beginPath() to "empty" the path list, otherwise the command Fill will fill the canvas with the previous path (background).

The code is as follows::

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 working: Here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.