控制台和画布清除自身

时间:2018-12-11 17:20:47

标签: javascript html google-chrome debugging canvas

我一直在尝试制作自己的Minesweeper版本,但由于某些原因,控制台和画布总是每隔500毫秒左右清除一次。我的计算机可能只是一个问题,但我已经尝试过重新启动和切换浏览器(Chrome,MS Edge)。 谁能帮我吗?

代码:

--reset-offsets --to-latest --execute
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var tileCount;
var mineCount;
var tileSize = canvas.width / tileCount;

var tiles = [];

function draw() {
  for (var i = 0; i < tileCount; i++) {
    for (var j = 0; j < tileCount; j++) {
      if (tiles[i][j].mine == true) {
        ctx.beginPath();
        ctx.fillText("M", i * 400 / tileCount, j * 400 / tileCount, 20);
        //"M" is for "mine"
      }
    }
  }
}

function init(tilecount, minecount) {
  console.log(tilecount);
  tileCount = tilecount;
  mineCount = minecount;
  for (var i = 0; i < tileCount; i++) {
    tiles[i] = [];
    for (var j = 0; j < tileCount; j++) {
      tiles[i][j] = {
        covered: true,
        flagged: false,
        numb: undefined,
        mine: false
      }
    }
  }

  var temp = mineCount,
    x, y;
  while (temp > 0) {
    x = Math.round(Math.random() * (tileCount - 1));
    y = Math.round(Math.random() * (tileCount - 1));
    if (tiles[x][y].mine == false) {
      tiles[x][y].mine = true;
      temp--;
    }
  }
  //delete temp, x, y;
  update();
}

function update() {
  draw();
}
body {
  background-color: lightgrey;
}

canvas {
  background-color: lightgrey;
  border-style: solid;
}

h1 {
  text-align: center;
}

* {
  font-family: verdana;
}

Stackoverflow不允许我发布此消息,因为它是“大部分代码”,我想我必须找到一种绕过其规则._。

的方法。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那是因为单击按钮时表单一直在提交。

一种解决方法是将事件传递给函数,然后使用preventDefault阻止表单提交:

HTML

<button onclick="init(event, this.form.tc.value, this.form.mc.value)">submit</button>

JS

function init(event, tilecount, minecount) {
  event.preventDefault();
  //
}

或者,为了与最佳实践保持一致,请删除内联JS,然后将侦听器添加到JS代码中的按钮上:

HTML

提交

JS

// Cache the form and button elements, and
// add a click listener to the button
var form = document.querySelector('form');
var button = document.querySelector('button');
button.addEventListener('click', init, false);

function init(e) {

  // Still preventDefault...
  e.preventDefault();

  // ...but assign the values from the cached form instead
  var tilecount = form.tc.value;
  var minecount = form.mc.value;

  //
}
相关问题