Javascript仅在JSFiddle上的script标签中起作用

时间:2019-01-30 03:33:23

标签: javascript html jsfiddle

我正在学习画布内容,并将一些代码复制到JSFiddle中。起初,我虽然将代码弄乱了,但是我将代码移到了方括号中,并且效果很好。然后,我将脚本从javascript框中移到了HTML框中的标签中,并且工作正常。为了在JSFiddle上的html区域之外工作,我需要调用其他名称吗?

Here是小提琴。堆栈溢出使我把它放在这里...

var ctx = null;
var tileW = 40;
var tileH = 40;
var mapW = 10;
var mapH = 10;
var currentSecond = 0;
var frameCount = 0;
var framesLastSecond = 0;

var gameMap = [
  0, 0, 0, 1, 0, 1, 1, 1, 0, 1,
  1, 1, 1, 1, 0, 1, 0, 1, 0, 1,
  1, 0, 0, 1, 1, 1, 0, 1, 1, 1,
  1, 1, 0, 0, 0, 0, 0, 1, 0, 0,
  1, 0, 0, 1, 0, 1, 1, 1, 0, 1,
  1, 0, 1, 1, 0, 1, 0, 0, 1, 1,
  1, 1, 0, 1, 0, 1, 1, 1, 1, 0,
  0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
  0, 1, 0, 0, 1, 1, 1, 1, 0, 1,
  0, 1, 1, 1, 1, 0, 0, 1, 1, 1
];
window.onload = function() {
  ctx = document.getElementById("game").getContext("2d");
  requestAnimationFrame(drawGame);
  ctx.font = "bold 10pt sans-serif";
};

function drawGame() {
  if (ctx == null) {
    console.log("I am broken");
    return;
  }

  var sec = Math.floor(Date.now() / 1000);
  if (sec != currentSecond) {
    currentSecond = sec;
    framesLastSecond = frameCount;
    frameCount = 1;
  } else {
    frameCount++;
  }

  for (var y = 0; y < mapH; y++) {
    for (var x = 0; x < mapW; x++) {
      switch (gameMap[((y * mapW) + x)]) {
        case 0:
          ctx.fillStyle = "#000000";
          break;
        default:
          ctx.fillStyle = "#ccffcc";
      }
      ctx.fillRect(x * tileW, y * tileH, tileW, tileH);
    }
  }
  ctx.fillstyle = "#ff0000";
  ctx.fillText("FPS: " + framesLastSecond, 10, 20);
  requestAnimationFrame(drawGame);
}

0 个答案:

没有答案