Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Javascript游戏添加到HTML Div中_Javascript_Html_Css - Fatal编程技术网

将Javascript游戏添加到HTML Div中

将Javascript游戏添加到HTML Div中,javascript,html,css,Javascript,Html,Css,我在将我的JS游戏加载到一个div时遇到了问题,最终应该在页眉下方显示游戏,但是它显示在页脚下方。有人知道我怎么解决这个问题吗?提前谢谢 JS文件 var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 10

我在将我的JS游戏加载到一个div时遇到了问题,最终应该在页眉下方显示游戏,但是它显示在页脚下方。有人知道我怎么解决这个问题吗?提前谢谢

JS文件

var animate = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function(callback) { window.setTimeout(callback, 1000/60) };

var canvas = document.createElement('canvas');
var width = 400;
var height = 600;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var topScore = 0;
var bottomScore = 0;
var game1 = document.getElementById("game");

window.onload = function() {
  document.body.appendChild(canvas);
  animate(step);

};

var step = function() {
  update();
  render();
  animate(step);
};

var update = function() {
};

var render = function() {
  context.fillStyle = "#ffd31d";
  context.fillRect(0, 0, width, height);
};
 <div class="game"></div>
 <script src="pong.js"></script>
HTML文件

var animate = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function(callback) { window.setTimeout(callback, 1000/60) };

var canvas = document.createElement('canvas');
var width = 400;
var height = 600;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var topScore = 0;
var bottomScore = 0;
var game1 = document.getElementById("game");

window.onload = function() {
  document.body.appendChild(canvas);
  animate(step);

};

var step = function() {
  update();
  render();
  animate(step);
};

var update = function() {
};

var render = function() {
  context.fillStyle = "#ffd31d";
  context.fillRect(0, 0, width, height);
};
 <div class="game"></div>
 <script src="pong.js"></script>

而不是

document.body.appendChild(canvas);
您需要将其附加到div

game1.appendChild(canvas);

将其附加到正文中只会将其添加到页面上的所有内容之后。

您使用
document.body.appendChild(canvas)将其附加到正文中。附加到其他地方。您可能需要使用
parentElement.insertBefore(canvas,beforeNode)。谢谢,我明白逻辑,这很有道理。但是,它仍然没有出现。你有git回购或其他方式来显示你的代码吗?谢谢你的调查。