Setting up an arena in canvas

Asked

Viewed 45 times

5

I’m setting up an arena using HTML/JS with the canvas.

I have the following code:

function montarArena() {
    var canvas;
    var heightCanvas = 498;
    var widthCanvas = 598;
    var qtdLinhas = $('#larguraCampo').val();
    var qtdColunas = $('#alturaCampo').val();
    var tamanhoLinha = widthCanvas / qtdLinhas;
    var tamanhoColuna = heightCanvas / qtdColunas;

    canvas = document.getElementById('imageView');
    context = canvas.getContext('2d');
    context.strokeStyle = '#000000';
    context.fillStyle = '#fff';
    context.clearRect(1, 1, widthCanvas, heightCanvas);

    console.log("tamColuna: " + tamanhoColuna + " tamLinha: " + tamanhoLinha + " QtdColunas: " + qtdColunas + " QtdLinhas: " + qtdLinhas);

    for (i = 0; i <= qtdLinhas; i++) {
      for (j = 0; j <= qtdColunas; j++) {
        context.strokeRect(j, i, tamanhoLinha * i, tamanhoColuna * j);
      }
    }
  
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input type="range" id="larguraCampo" value="1" min="1" max="25" onchange="montarArena()" />
<input type="range" id="alturaCampo" value="1" min="1" max="25" onchange="montarArena()" />
<br/><br/><br/><br/><br/><br/>
<canvas id="imageView" width="600" height="500"></canvas>

As the number of lines is increased, the arena gets crooked.... As follows::

inserir a descrição da imagem aqui

I need it to fit, like a real table:

inserir a descrição da imagem aqui

I’m not realizing where I’m going wrong.

1 answer

3


You had changed the logic of the argument, it must be

context.strokeRect(tamanhoLinha * j, tamanhoColuna * i, tamanhoLinha, tamanhoColuna);

The way you had him draw N all squares starting from the upper left corner at the coordinate point [i, j], which means that the first square started at [0, 0], the second in [1, 1], etc... and so lagged/shifted. What you were varying was the area of each square.

Changing as I suggest, you create squares all with the same area and with the corner of the square repositioned to [tamanhoLinha * j, tamanhoColuna * i].

  • Very good @Sergio, that’s right! What the lack of a table test does not rs. A single correction, Oce ended up reversing the order of tamanhoLinha * j and tamanhoColuna * i, the correct would be tamanhoLinha * i and tamanhoColuna * j,

Browser other questions tagged

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