【问题标题】:Console and canvas clear themselves控制台和画布清除自己
【发布时间】:2019-05-12 17:51:36
【问题描述】:

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

代码:

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;
}
<!DOCTYPE html>
<html>

<head>
  <title>MINESWEEPER</title>
</head>

<body>

  <h1>MINESWEEPER</h1>
  <br>
  <form>
    Tiles:<input type="text" name="tc" value="10"> Mines:
    <input type="text" name="mc" value="40">
    <button onclick="init(this.form.tc.value, 
    this.form.mc.value)">submit</button>
  </form>
  <br>
  <canvas id="myCanvas" width="400" height="400"></canvas>

</body>

</html>

Stackoverflow 不允许我发布此内容,因为它“主要是代码”,我想我必须想办法绕过他们的规则._.

【问题讨论】:

  • 如果您在发布代码时遇到问题,请尝试压缩您正在做的事情。例如,而不是像图像和东西这样的所有部分,只留下瓷砖和一个单一的图像。这可能有点痛苦,但这是值得的。有时它甚至会让您发现问题的原因!

标签: javascript html google-chrome debugging canvas


【解决方案1】:

如果我理解正确,那是因为当您单击按钮时表单不断提交。

解决这个问题的一种方法是将事件传递给函数,然后使用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;

  //
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2021-12-10
    • 2011-02-28
    相关资源
    最近更新 更多