Показать сообщение отдельно
  #8 (permalink)  
Старый 16.05.2021, 13:49
Аспирант
Отправить личное сообщение для prototip Посмотреть профиль Найти все сообщения от prototip
 
Регистрация: 15.05.2021
Сообщений: 35

рони, тут я с вами согласен. Обьясните пожалуйста почему, когда я выношу эти переменные ширины и высоты в глобальную переменную, код перестает работать?
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let widthInput = document.getElementById("width");
let heightInput = document.getElementById("height");

let width = canvas.width;
let height = canvas.height;
  let n = width / 10;
  let m = height / 10;

let xRect= 10;
let yRect= 10;
    
let mas = [];
let count = 0;
let timer;

canvas.onclick = function (event) {
  let x = event.offsetX; 
  let y = event.offsetY;

  x = Math.floor(x / 10);
  y = Math.floor(y / 10);

  mas[y][x] = 1; 
  drawField();
};

function resizeCanvas(){
canvas.width = widthInput.value;
canvas.height = heightInput.value;
  goLife();
  }

function goLife() {

  for (let i = 0; i < m; i++) {
    mas[i] = []; 
    for (let j = 0; j < n; j++) {
      mas[i][j] = 0;
    }
  }
}
goLife();

function drawField(){
  
  ctx.clearRect(0, 0, width, height);
  for (let i = 0; i < m; i++) {
       for (let j = 0; j < n / 10; j++) {

      if (mas[i][j] === 1) {
        ctx.fillRect(j * xRect, i * yRect, 10, 10);
      }
    }
  }
}

function startLife() {
  let mas2 = [];
            for (let i = 0; i < m; i++) {
                mas2[i] = [];
                for (let j = 0; j < n; j++) {
                    let neighbors = [-1, 1].reduce((a, b) => {
                    b = mas[i + b];
                    if(b === undefined) 
                      return a;
                    let num = b[j];
                    if(b[j + 1] !== undefined) {
                      num += b[j + 1]
                    }
                    if(b[j - 1] !== undefined) {
                      num += b[j - 1]
                    }
                    return a + num;
                    }, 0);
                    neighbors = [-1, 1].reduce((a, b) => a += mas[i][j + b] !== undefined && mas[i][j + b], neighbors);
                    if (neighbors == 2 || neighbors == 3) {
                        mas2[i][j] = 1;
                    } else {
                        mas2[i][j] = 0;
      };
                }
            }
            mas = mas2;
            drawField();
            count++;
            document.getElementById('count').innerHTML = count;
            timer = setTimeout(startLife, 300);
        }
function pauseLife(){
  clearInterval(timer)
}

function stopLife(){
  
}

document.getElementById("create").onclick = resizeCanvas;
document.getElementById("start").onclick = startLife;
document.getElementById("pause").onclick = pauseLife;
document.getElementById("stop").onclick = stopLife;
Ответить с цитированием