I have created a game with Phaser 3. I have it stored as a.js file in my working directory. I want the game to start when the start button is clicked on my.html index page. What am I doing wrong here?
The only thing I need to happen is for the game to run when the button is clicked, just as if I had included the script in the body
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- Title of our Page -->
<title>Video Game</title>
<!-- Phaser 3 link here -->
<script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<!-- CSS For our page -->
<style type="text/css">
html, body {
margin: 0;
width: 1000px !important;
height: 750px !important;
}
script {
width: 1000px !important;
height: 750px !important;
}
</style>
</head>
<body>
<script>
var skateGame = require('skateboarding.js');
</script>
<input type = "button" onclick = "skateGame" value = "Skateboarding" />
</body>
</html>
try this.
in your .html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- Title of our Page -->
<title>Video Game</title>
<!-- Phaser 3 link here -->
<script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<!-- CSS For our page -->
<style type="text/css">
html,
body {
margin: 0;
width: 1000px !important;
height: 750px !important;
}
script {
width: 1000px !important;
height: 750px !important;
}
#startGame {
background-color: #4caf50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<input type="button" id="startGame" value="Start Game" />
<script src="skateBoarding.js"></script>
</body>
</html>
and in skateBoarding.js
var startButton = document
.querySelector("#startGame")
.addEventListener("click", () => {
this.startGame();
});
// Function that start game
startGame = () => {
console.log("Game is starting");
};
let me know if this works. and try to keep your html and js in separate files.
By using onclick = "skateGame" your are asking javascript to do something with var skateGame wich does not make sense. Try:
<button id="btn1" type="button"/>
<script type="text/javascript">
var myBtn= document.getElementById('btn1');
myBtn.onclick = function(){
Your javascript code
}
</script>
Tell me if it works or not
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.