Как сделать изменение значения переменной глобально ? JavaScript

counter должен менять значение при нажатии на красную кнопку , при нажатии на зеленую кнопку , значение counter должно выводится в консоль

let context = canvas.getContext('2d');

let width = 800;
let height = 600;

canvas.width = width;
canvas.height = height;

context.fillStyle = '#2d2d2d';
context.font = '30px Arial';
context.fillText('dont touch red button!', 50, 50);
context.fillStyle = 'red';
context.fillRect(50, 100, 100, 100);
context.fillStyle = 'green';
context.fillRect(200, 100, 100, 100);

canvas.onmousedown = function (event) {
  let mouseX = event.clientX;
  let mouseY = event.clientY;
  let counter = 0;
  if (
    mouseX >= 50 &&
    mouseX <= 50 + 100 &&
    mouseY >= 100 &&
    mouseY <= 100 + 100
  ) {
    counter++;
  } else if (
    mouseX >= 200 &&
    mouseX <= 200 + 100 &&
    mouseY >= 100 &&
    mouseY <= 100 + 100
  ) {
    console.log(counter);
  }
};```


Ответы (1 шт):

Автор решения: Евгений Лис

Переместите определение переменной(let counter = 0;) в глобальную область

→ Ссылка