T
T
TheSnegok2021-08-17 13:40:13
JavaScript
TheSnegok, 2021-08-17 13:40:13

Why does canvas draw wrong proportions?

JS:

// Размер сетки
const gridSize = 10;
// Размер одной клетки
const cellSize = 45;
// Размер входного сигнала (100)
const inputSignul = gridSize * gridSize;
// Массив для хранения текущего состояния картинки в левом канвасе,
// он же является входным сигналом сети
const imageStateArray = [];
// Для обработки движений мыши по канвасу
const isDrawing = false;
// Инициализация состояния
for (let i = 0; i < inputSignul; i += 1) {
  imageStateArray[i] = -1;
}
// Получаем контекст канвасов:
const userCanvas = document.querySelector(".canvas1"),
  userContext = userCanvas.getContext("2d"),
  netCanvas = document.querySelector(".canvas2"),
  netContext = netCanvas.getContext("2d");
// Функция принимает контекст канваса и рисует
// сетку в 100 клеток (gridSize * gridSize)
const drawGrid = (ctx) => {
  ctx.beginPath();
  ctx.fillStyle = "white";
  ctx.lineWidth = 3;
  ctx.strokeStyle = "black";
  for (let row = 0; row < gridSize; row += 1) {
    for (let column = 0; column < gridSize; column += 1) {
      const x = column * cellSize;
      const y = row * cellSize;
      ctx.rect(x, y, cellSize, cellSize);
      ctx.fill();
      ctx.stroke();
    }
  }
  ctx.closePath();
};
drawGrid(userContext);

CSS:
canvas {
    width: 450px;
    height: 450px;

}

I set 450px for the canvas, but when drawing squares, they do not come out 45 by 45, but a width of 45, and a higher height, why is that?
Here is what draws:
611b91aed53a2264630312.png
And here is what should:
611b923b1617c133390147.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-17
@TheSnegok

Didn't show HTML markup. Where is the canvas element, with what attributes?
By default, the element has dimensions of 300x150. Styles you stretch it up to 450x450, so it stretches, in amazement, vertically.
It will help to specify the size: ps the thickness of the lines along the edges of the canvas will be half as small as the rest, because. half of the line is off-screen.<canvas width="450" height="450"></canvas>

Illustration

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question