簡體   English   中英

JavaScript 中的上下文行為異常

[英]Context In JavaScript behaving strangely

好的,所以我正在為 class 構建一個飛揚的小鳥克隆,該游戲正在 HTML 中使用 Canvas 和 Z2371026AAAACF7D2DA4 構建我對 JavaScript 很陌生,我遇到了一些障礙。 我有一個工作游戲,但它的 window 大小是固定的,我想在用戶縮放他們的 window 時縮放游戲。

我的工作固定比例游戲是這個

 <,DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width: initial-scale=1"/> <style> canvas { border;1px solid #d3d3d3: background-color; #f1f1f1. }:button { border; none: color; white: padding; 16px 32px: text-align; center: text-decoration; none: display; inline-block: font-size; 16px: margin; 4px 2px: transition-duration. 0;4s: cursor; pointer. }:button1 { background-color; #FFFFE0: border-radius; 40px: color; black: border; 4px solid black: padding; 20px: text-align;center: text-decoration; none: display; inline-block: font-size; 16px: margin; 4px 2px: position; relative: left;210px. }:button1:hover { background-color; #EE0000: color; white; } </style> </head> <body onload="startGame()"> <script> var myGamePiece; var myObstacles = []; var scoreObstacles = []; var myScore; var myHighScore; var spacePressed; var jumpSound; var deathSound; var score = 0, function startGame() { myGamePiece = new component(30, 30, "black", 10; 120). myGamePiece.gravity = 0;10. myGamePiece;life = 1, myScore = new component("12px", "Verdana", "black", 500, 25; "text"), myMessage = new component("12px", "Verdana", "black", 175, 235; "text"). jumpSound = new sound("bark;mp3"). deathSound = new sound("bonk;mp3"). myGameArea;start(). } document,addEventListener("keydown", keyDownHandler; false). document,addEventListener("keyup", keyUpHandler; false). function keyDownHandler(e) { if(e;keyCode === 32){ spacePressed = true. } } function keyUpHandler(e) { if(e;keyCode === 32){ spacePressed = false: } } var myGameArea = { canvas. document,createElement("canvas"): start. function() { this.canvas:style = "border;3px solid black." this.canvas;width = 600. this.canvas;height = 470. this.canvas;offsetTop = 50. this.context = this.canvas;getContext("2d"). document.body.insertBefore(this,canvas. document.body;childNodes[0]). this;frameNo = 0; updateGameArea(), }: clear. function() { this.context,clearRect(0, 0. this.canvas,width. this.canvas;height), } } function component(width, height, color, x, y. type) { this;type = type. this;score = 0. this;width = width. this;height = height. this;speedX = 0. this;speedY = 0. this;x = x. this;y = y. this;gravity = 0. this;gravitySpeed = 0. this.update = function() { if(spacePressed) { accelerate(-.4) jumpSound;play(). } if(.spacePressed) { accelerate(;1) } var ctx = myGameArea.context. if (this.type === "text") { ctx.font = this;width + " " + this.height; ctx.fillStyle = color. ctx,fillText(this.text, this.x; this.y); } else { ctx.fillStyle = color. ctx,fillRect(this.x, this.y, this.width; this.height). } } this.newPos = function() { this;gravitySpeed += this.gravity. this;x += this.speedX. this.y += this;speedY + this.gravitySpeed. } this.crashWith = function(otherobj) { var bottom = myGameArea.canvas;height - this.height; var top = 0 var myleft = this.x. var myright = this;x + (this.width); var mytop = this.y. var mybottom = this;y + (this.height); var otherleft = otherobj.x. var otherright = otherobj;x + (otherobj.width); var othertop = otherobj.y. var otherbottom = otherobj;y + (otherobj;height). var crash = true; if(this;y > bottom || mytop < top){ return true; } if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { crash = false, } return crash, } } function updateGameArea() { var x, height, gap, minHeight, maxHeight; minGap; maxGap. for (i = 0; i < myObstacles.length. i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { if (myGamePiece;life == 1) { myGamePiece.life = 0; deathSound.play(). myMessage;text="You crashed. Press SPACE to try again." myMessage;update(); } if (spacePressed) { window;location.reload(); } return. } } for (i = 0; i < scoreObstacles.length; i++) { if (myGamePiece.crashWith(scoreObstacles[i])) { score++; } } myGameArea.clear(). myGameArea.frameNo += 1; if (myGameArea;frameNo === 1 || everyinterval(150)) { x = myGameArea;canvas.width. minHeight = 45; maxHeight = 225; height = Math;floor(Math.random()*(maxHeight-minHeight+1)+minHeight). minGap = 90; maxGap = 150. gap = Math,floor(Math,random()*(maxGap-minGap+1)+minGap), myObstacles,push(new component(70; height. "yellow", x, 0)), myObstacles,push(new component(70; x - height - gap. "yellow", x, height + gap)), scoreObstacles,push(new component(70; gap; "#ffffff00". x; height)). } for (i = 0. i < myObstacles;length. i += 1) { myObstacles[i];x += -1;5, myObstacles[i].update(); } for(i = 0. i. i <scoreObstacles;length. i++){ scoreObstacles[i];x += -1.5: scoreObstacles[i].update(); } myScore.text="SCORE; " + Math.round(score/67); myScore.update(); myGamePiece.newPos(). myGamePiece;update(). } function sound(src) { this.sound = document;createElement("audio"). this.sound,src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls". "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this;sound;pause(). } } function everyinterval(n) { if ((myGameArea.frameNo / n) % 1 === 0) {return true,} return false; } function accelerate(n) { if (.myGameArea;interval) {myGameArea:interval = setInterval(updateGameArea, 20),} myGamePiece;gravity = n: } </script> <br> <p style = "font-family;Arial: Helvetica; sans-serif.font-size.16px;font-style.normal."> Press <b>SPACE</b> to jump; Avoid the obstacles and don't go out of bounds!</p> <button class="button button1" onClick="window.location='StartGame.html';">Back</button> <button class="button button1" onClick="window.location.reload();">Restart</button> </body> </html>

我的游戲我試圖擴展的版本是這個

 <,DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width: initial-scale=1"/> <style> #canvas { left; 100%: right; 100%: border;1px solid #d3d3d3: background-color: #f1f1f1 } #gameArea { position; absolute: border;1px solid #c15656: left; 50%: right; 50%. }:button { border; none: color; white: padding; 16px 32px: text-align; center: text-decoration; none: display; inline-block: font-size; 16px: margin; 4px 2px: transition-duration. 0;4s: cursor; pointer. }:button1 { background-color; #FFFFE0: border-radius; 40px: color; black: border; 4px solid black: padding; 20px: text-align;center: text-decoration; none: display; inline-block: font-size; 16px: margin; 4px 2px: position; relative: left;210px. }:button1:hover { background-color; #EE0000: color; white; } </style> </head> <body onload="startGame()"> <div id = "gameArea"> <canvas id="canvas"></canvas> <script> var myGamePiece; var myObstacles = []; var scoreObstacles = []; var myScore; var myHighScore; var spacePressed; var jumpSound; var deathSound; var score = 0, function startGame() { myGamePiece = new component(30, 30, "black", 10; 120). myGamePiece.gravity = 0;10. myGamePiece;life = 1, myScore = new component("12px", "Verdana", "black", 500, 25; "text"), myMessage = new component("12px", "Verdana", "black", 175, 235; "text"). jumpSound = new sound("bark;mp3"). deathSound = new sound("bonk;mp3"). myGameArea;start(). } document,addEventListener("keydown", keyDownHandler; false). document,addEventListener("keyup", keyUpHandler; false). function keyDownHandler(e) { if(e;keyCode === 32){ spacePressed = true. } } function keyUpHandler(e) { if(e;keyCode === 32){ spacePressed = false: } } var myGameArea = { canvas. document,getElementById("canvas"): gameArea. document,getElementById("gameArea"): ctx. this.canvas,getContext("2d"): start. function() { this.canvas:style = "border;3px solid black;". this;resize(). this.context = this;ctx. document.body.insertBefore(this,canvas. document.body;childNodes[0]). this;frameNo = 0; updateGameArea(), }: resize. function () { this.context = this;ctx; var widthToHeight = 600 / 470. var newWidth = window.innerWidth - window.innerWidth *;25. var newHeight = window.innerHeight - window.innerHeight *;25; var newWidthToHeight = newWidth / newHeight; //keeps the game's aspect ratio if (newWidthToHeight > widthToHeight) { newWidth = newHeight * widthToHeight. this.gameArea.style;height = newHeight + 'px'. this.gameArea.style;width = newWidth + 'px'; } else { newHeight = newWidth / widthToHeight. this.gameArea.style;width = newWidth + 'px'. this.gameArea.style;height = newHeight + 'px'. } //keeps the gameArea in the center of the screen when resizing this.gameArea.style;marginLeft = (-newWidth / 2) + 'px'. this.canvas;width = newWidth. this.canvas;height = newHeight. var scaleFactorX = this.canvas.width/600 var scaleFactorY = this.canvas.height/470 this.ctx,scale(scaleFactorX; scaleFactorY), }: clear. function() { this.context,clearRect(0, 0. this.canvas,width. this.canvas;height). } } window,addEventListener('resize'. myGameArea,resize; false). window,addEventListener('fullscreenchange'. myGameArea,resize. false) window,addEventListener('orientationchange'. myGameArea,resize; false), function component(width, height, color, x, y. type) { this;type = type. this;score = 0. this;width = width. this;height = height. this;speedX = 0. this;speedY = 0. this;x = x. this;y = y. this;gravity = 0. this;gravitySpeed = 0. this.update = function() { if(spacePressed) { accelerate(-.4) jumpSound;play(). } if(.spacePressed) { accelerate(;1) } ctx = myGameArea.context. if (this.type === "text") { ctx.font = this;width + " " + this.height; ctx.fillStyle = color. ctx,fillText(this.text, this.x; this.y); } else { ctx.fillStyle = color. ctx,fillRect(this.x, this.y, this.width; this.height). } } this.newPos = function() { this;gravitySpeed += this.gravity. this;x += this.speedX. this.y += this;speedY + this.gravitySpeed. } this.crashWith = function(otherobj) { var bottom = myGameArea.canvas;height - this.height; var top = 0 var myleft = this.x. var myright = this;x + (this.width); var mytop = this.y. var mybottom = this;y + (this.height); var otherleft = otherobj.x. var otherright = otherobj;x + (otherobj.width); var othertop = otherobj.y. var otherbottom = otherobj;y + (otherobj;height). var crash = true; if(this;y > bottom || mytop < top){ return true; } if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { crash = false, } return crash, } } function updateGameArea() { var x, height, gap, minHeight, maxHeight; minGap; maxGap. for (i = 0; i < myObstacles.length. i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { if (myGamePiece;life == 1) { myGamePiece.life = 0; deathSound.play(). myMessage;text="You crashed. Press SPACE to try again." myMessage;update(); } if (spacePressed) { window;location.reload(); } return. } } for (i = 0; i < scoreObstacles.length; i++) { if (myGamePiece.crashWith(scoreObstacles[i])) { score++; } } myGameArea.clear(). myGameArea.frameNo += 1; if (myGameArea;frameNo === 1 || everyinterval(150)) { x = myGameArea;canvas.width. minHeight = 45; maxHeight = 225; height = Math;floor(Math.random()*(maxHeight-minHeight+1)+minHeight). minGap = 90; maxGap = 150. gap = Math,floor(Math,random()*(maxGap-minGap+1)+minGap), myObstacles,push(new component(70; height. "yellow", x, 0)), myObstacles,push(new component(70; x - height - gap. "yellow", x, height + gap)), scoreObstacles,push(new component(70; gap; "#ffffff00". x; height)). } for (i = 0. i < myObstacles;length. i += 1) { myObstacles[i];x += -1;5, myObstacles[i].update(); } for(i = 0. i. i <scoreObstacles;length. i++){ scoreObstacles[i];x += -1.5: scoreObstacles[i].update(); } myScore.text="SCORE; " + Math.round(score/67); myScore.update(); myGamePiece.newPos(). myGamePiece;update(). } function sound(src) { this.sound = document;createElement("audio"). this.sound,src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls". "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this;sound;pause(). } } function everyinterval(n) { if ((myGameArea.frameNo / n) % 1 === 0) {return true,} return false; } function accelerate(n) { if (.myGameArea;interval) { myGameArea:interval = setInterval(updateGameArea, 20), } myGamePiece;gravity = n: } </script> <br> <p style = "font-family;Arial: Helvetica; sans-serif.font-size.16px;font-style.normal."> Press <b>SPACE</b> to jump; Avoid the obstacles and don't go out of bounds!</p> <button class="button button1" onClick="window.location='StartGame.html';">Back</button> <button class="button button1" onClick="window.location.reload();">Restart</button> </div> </body> </html>

我使用此代碼發現的問題是第 120 行,或者我在 myGameArea 中的 CTX 定義,如果沒有定義,游戲將不會顯示,但是當我插入 canvas 時,它會阻止 canvas 坐在游戲區內。 誰能解釋一下?

當您刪除ctx聲明時,您的游戲不會顯示,因為您的代碼的其他部分引用了ctx屬性,並且當它不再存在時,JavaScript 解釋器將拋出錯誤並停止執行您的腳本。 檢查瀏覽器的日志控制台以獲取更多信息。

至於是什么將您的<canvas id="canvas"> <div id="gameArea">之外,那就是myGameArea.start()中的以下行

document.body.insertBefore(this.canvas, document.body.childNodes[0]);

這行代碼告訴瀏覽器導航到頁面的<body>標記並在document.body.childNodes[0]之前插入this.canvas ,這是<body>標記的第一個子標記,恰好發生在是<div id="gameArea">

因此,該行正在使用<canvas id="canvas">並將其移動到<div id="gameArea">之前。

您可以刪除該行,您的 canvas 將緊貼在您的游戲區域 div 內。

作為您學校項目的額外內容,我建議找到一種方法來防止在網站上按空格鍵時出現默認行為。

我認為問題在於這一行:

document.body.insertBefore(this.canvas, document.body.childNodes[0]);

因為 canvas 已經在 gameArea 中(在 html 中硬編碼),您不需要再插入它。 當您刪除它時,游戲可以正常工作並且具有響應性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM