I have made this simple program which currently triggers a red circle to travel upwards if the question answered is correctly ,which in turn increases the score.I have now decided to introduce a timer which should display in the centre of the canvas and when the timer runs out it should display and alert with the score they got and to restart.The problem I have is not the timer working,but its not displaying as it is below the canvas,where you’ll see a timer counting down.If you test the program it clearly shows the “count” in the canvas,but because count is not linked to an id it gets very confusing for me,i don’t know how to go about it, can someone please help me out.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
width: 100%;
background-color: black;
}
</style>
</head>
<h1 align="center"></h1>my jumper game </h1>
<p align="center"> </p>A Fun flappy-bird like game</p><//p>
<div>
<p>What is 10 times 4 ? <input type ="number" id="Q1"></p>
<p>What is 5 * 5 ? <input type ="number" id="Q2"></p>
<p>What is 5 * 3 ? <input type ="number" id="Q3"></p>
<button onclick="submitAnswers()">Submit</button>
</div>
<canvas id="canvas" width="900" height="400">
Your browser does not support the HTML5 canvas tag.
</canvas>
<br> </br>
<body onload="startGame()">
<div>Time left = <span id="timer"></span>
<script>
window.onload = function() {
let btn = document.getElementById("submitAnswers");
btn.onclick = jump;
};
document.getElementById('timer').innerHTML =
01 + ":" + 11;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
function submitAnswers(){
const answer1 = document.querySelector("#Q1").value
if (answer1 == 40)
jump();
const answer2 = document.querySelector("#Q2").value
if (answer2 == 25)
jump();
}
let count = 0;
let timer = 'timer';
function jump() {
count += 1;
//changing the y position
y -= 25;
//clearing the canvas
context.clearRect(0, 0, 600, 400);
//redrawing the circle
context.beginPath();
context.arc(x, y, 50, 0, 2 * Math.PI);
context.fillStyle="red";
context.fill();
//drawing the count value
context.font = '25px Arial';
context.fillStyle = 'white';
context.fillText("Count: " + count, 20, 30);
context.font = '25px Arial';
context.fillStyle = 'white';
context.fillText("Timer: " + timer, 200, 30);
if (y <= 0) {
y = 350 ;
}
window.requestAnimationFrame(draw);
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var x = 450;
var y = 350;
</script>
</body>
</html>