将Javascript游戏添加到HTML Div中
我在将我的JS游戏加载到一个div时遇到了问题,最终应该在页眉下方显示游戏,但是它显示在页脚下方。有人知道我怎么解决这个问题吗?提前谢谢 JS文件将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
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回购或其他方式来显示你的代码吗?谢谢你的调查。