'Button is not found in HTML
All I'm working on a small game using node js, so I have a button and when I press the button a rectangle should be drawn in the canvas that is present on my Html page.
But I think my node js is loading faster than my Html, how can I make all my Html elements load and then node js execute.
Here is my code
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sanke Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button type="submit" id = "smallButton" name="button">Draw</button>
<canvas id="canvas" tabindex="0" width="640" height="480"></canvas>
<script src="userInput.js"></script>
<script src="snake.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
snake.js
const gameBoard = document.getElementById("canvas");
const gameBoard_ctx = canvas.getContext("2d");
const bun = document.getElementById("smallButton");
//Generating Random Coordinate
function randomCoordinates(){
var startX = 40+Math.random()*560;
var startY = 40+Math.random()*400;
return [startX, startY];
}
// Drawing snake
function drawSnakePart(snakePart){
gameBoard_ctx.fillStyle = 'lightblue';
gameBoard_ctx.strokestyle = 'darkblue';
gameBoard_ctx.fillRect(snakePart[0], snakePart[1], 10, 10);
gameBoard_ctx.strokeRect(snakePart[0], snakePart[1], 10, 10)
}
function drawSnake(){
for(var i=0; i<8; i++){
drawSnakePart(randomCoordinates());
}
}
bun.addEventListener("click", function(){
alert("clicked");
drawSnake();
})
app.js
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
//Responding to Root request
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html")
})
//Responds if client request is made
app.get("/client.js", function(req, res){
res.sendFile(__dirname + "/client.js");
})
//Responds to css req
app.get("/styles.css", function(req, res){
res.sendFile(__dirname + "/styles.css");
})
//Responds to keyMovements
app.get("/userInput.js", function(req, res){
res.sendFile(__dirname+"/userInput.js");
})
app.get("/snake.js", function(req, res){
res.sendFile(__dirname+"/snake.js");
})
io.on('connection', function(socket){
console.log("User is connected");
socket.on("disconnect", function(){
console.log("User Disconnected");
})
socket.emit("serverToClient", "Hello World");
socket.on("clientToServer", function(event){
console.log(event);
})
socket.on("clientToClient", data => {
socket.broadcast.emit("serverToClient", data);
})
})
server.listen(3000, function(){
console.log("Listening to port 3000");
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
