In w3schools there is a basic game and I can't figure out how to make the piece or object a circle. I'm so confused and have tried everything but it didn't work. How can I use fill circle or another method for this? I'm new to canvas.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40,
"text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,
document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
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() {
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.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
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 ((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])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-
minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x,
height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)"
onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>
</body>
</html>
Change your function component() and startGame() to this one.
You can draw cirlce with arc method.
Details: https://www.w3schools.com/tags/canvas_arc.asp
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120, "player");
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40,
"text");
myGameArea.start();
}
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() {
ctx = myGameArea.context;
ctx.fillStyle = color;
if (this.type == "text") { // text
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else if (this.type == "player") { // player
ctx.beginPath();
ctx.arc(this.x, this.y, 35,0,2*Math.PI);
ctx.fill();
ctx.stroke();
} else { // wall
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.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
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 ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
Related
i'm a beginner to javascript, so there might be something that i dont know yet, but i'm trying
to make a logo in script, in html. this is the code to make a square that moves, but i need a triangle for my logo: also, i need to know how to make a circle in javascript for the same reason. please help me out.
var myGamePiece;
var myGamePiece2;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "yellow", 10, 240);
myGamePiece2 = new component(30, 10, "orange", 18, 250);
myGamePiece3 = new component(30, 10, "black", 18, 250);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
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.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
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 ((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])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].speedX = -1;
myObstacles[i].newPos();
myObstacles[i].update();
}
myScore.text = "SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
myGamePiece2.newPos();
myGamePiece2.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {
return true;
}
return false;
}
function moveup() {
myGamePiece.speedY = -1;
myGamePiece2.speedY = -1;
myGamePiece3.speedY = -1;
}
function movedown() {
myGamePiece.speedY = 1;
myGamePiece2.speedY = 1;
myGamePiece3.speedY = 1;
}
function moveleft() {
myGamePiece.speedX = -1;
myGamePiece2.speedX = -1;
myGamePiece3.speedX = -1;
}
function moveright() {
myGamePiece.speedX = 1;
myGamePiece2.speedX = 1;
myGamePiece3.speedX = 1;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece2.speedX = 0;
myGamePiece2.speedY = 0;
myGamePiece3.speedX = 0;
myGamePiece3.speedY = 0;
}
canvas {
border: 1px solid #d3d3d3;
background-color: #0033cc;
}
<!DOCTYPE html>
<html>
<head>
<title>Flappy!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-black.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="icon" type="image/png" href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/160px-Apple_logo_black.svg.png" sizes="16x16">
<link rel="canonical" href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/160px-Apple_logo_black.svg.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body onload="startGame()">
<div class="w3-center w3-green w3-text-black">
<h1>Flappy!</h1>
<h4>the first game that tech gaming put out..., Flappy!</h4>
<div style="text-align:center;width:480px;">
<button onmousedown="moveup()" onmouseup="clearmove()" ontouchstart="moveup()">UP</button><br><br>
<button onmousedown="moveleft()" onmouseup="clearmove()" ontouchstart="moveleft()">LEFT</button>
<button onmousedown="moveright()" onmouseup="clearmove()" ontouchstart="moveright()">RIGHT</button><br><br>
<button onmousedown="movedown()" onmouseup="clearmove()" ontouchstart="movedown()">DOWN</button>
</div>
<p>The score will count one point for each split-second you manage to "stay alive".</p>
</div>
</body>
</html>
theres probably some code i dont know but like i said i dont know very much javascript.
I added the code below at the end of your component.update() to draw a circle and triangle. I got this from the Mozilla docs on drawing shapes, found here. See the full modified code as well farther below.
Added Code:
//DRAW CIRCLE
ctx.beginPath();
var x = 50; // x coordinate
var y = 150; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI + (Math.PI); // End point on circle
var anticlockwise = 0; // clockwise or anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.fillStyle = "red";
ctx.fill();
//DRAW TRIANGLE
ctx.beginPath();
ctx.moveTo(50, 30);
ctx.lineTo(25, 75);
ctx.lineTo(75, 75);
ctx.fillStyle = "black";
ctx.fill();
Full Modified Code:
<!DOCTYPE html>
<html>
<title>Flappy!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-black.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="icon" type="image/png" href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/160px-Apple_logo_black.svg.png" sizes="16x16"><link rel="canonical" href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/160px-Apple_logo_black.svg.png"/>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<div class="w3-center w3-green w3-text-black">
<h1>Flappy!<h1>
<h4>the first game that tech gaming put out..., Flappy!</h4>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #0033cc;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myGamePiece2;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "yellow", 10, 240, "triangle");
myGamePiece2 = new component(30, 10, "orange", 18, 250);
myGamePiece3 = new component(30, 10, "black", 18, 250);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
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);
}
//*************************MODIFIED CODE BELOW***********************************
//DRAW CIRCLE
ctx.beginPath();
var x = 50; // x coordinate
var y = 150; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI + (Math.PI); // End point on circle
var anticlockwise = 0; // clockwise or anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.fillStyle = "red";
ctx.fill();
//DRAW TRIANGLE
ctx.beginPath();
ctx.moveTo(50, 30);
ctx.lineTo(25, 75);
ctx.lineTo(75, 75);
ctx.fillStyle = "black";
ctx.fill();
//*************************MODIFIED CODE ABOVE***********************************
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
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 ((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])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].speedX = -1;
myObstacles[i].newPos();
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
myGamePiece2.newPos();
myGamePiece2.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function moveup() {
myGamePiece.speedY = -1;
myGamePiece2.speedY = -1;
myGamePiece3.speedY = -1;
}
function movedown() {
myGamePiece.speedY = 1;
myGamePiece2.speedY = 1;
myGamePiece3.speedY = 1;
}
function moveleft() {
myGamePiece.speedX = -1;
myGamePiece2.speedX = -1;
myGamePiece3.speedX = -1;
}
function moveright() {
myGamePiece.speedX = 1;
myGamePiece2.speedX = 1;
myGamePiece3.speedX = 1;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece2.speedX = 0;
myGamePiece2.speedY = 0;
myGamePiece3.speedX = 0;
myGamePiece3.speedY = 0;
}
</script>
<div style="text-align:center;width:480px;">
<button onmousedown="moveup()" onmouseup="clearmove()" ontouchstart="moveup()">UP</button><br><br>
<button onmousedown="moveleft()" onmouseup="clearmove()" ontouchstart="moveleft()">LEFT</button>
<button onmousedown="moveright()" onmouseup="clearmove()" ontouchstart="moveright()">RIGHT</button><br><br>
<button onmousedown="movedown()" onmouseup="clearmove()" ontouchstart="movedown()">DOWN</button>
</div>
<p>The score will count one point for each split-second you manage to "stay alive".</p>
</div>
</body>
</html>
I have made a post on this before however, it was not in a canvas, but when you try to apply this to a canvas It gives an error along the lines of Cant change the color of undefined so I thought it was an error of the way I defined it so I would add it to a class then run it as changing the color of all elements in the class, but when I try it the canvas just disappears.. but getting to the point is there an easy way to change the color of a HTML element in a canvas or am I just crazy
Code
var myGamePiece = el.classList.add("class1");
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
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() {
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.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
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 ((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])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text = "SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {
return true;
}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
function Test() {
document.getElementsByClassName("class1").style.background = "yellow";
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
.class1 {}
<body onload="startGame()">
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p> Credit To W3Schools.com </p>
<button onclick="test">Click To Change Player's Color</button>
</body>
The code starts with: var myGamePiece = el.classList.add("class1");el is not defined but anyway myGamePiece needs to be a component as created in startGame, it is not an ordinary HTML element.
It is the creation of that component that the color is set. Currently the color is hardcoded as 'red'. To change the color you need to set a variable, let's call it playerColor, and use that in the component creation call rather than 'red'.
You are using function test to set up a color so let's change the test function to do that, but you need to get that color set up before startGame otherwise the canvas will have the incorrect color for the piece (or no set color).
var playersColor = "red"; //the default value if the player doesn't change it
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, playersColor, 10, 120);//use playersColor
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
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() {
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.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
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 ((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])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text = "SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {
return true;
}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
function test() {
playersColor = "yellow";
}
<body>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p> Credit To W3Schools.com </p>
<button onclick="test()">Click To Change Player's Color</button>
<button onclick="startGame();">Click to start the game</button>
</body>
...............................................................................
Although the following errors are not fundamentally what is causing non-changing of the player's color, they contain some coding errors which it might be helpful to point out for the future.
<button onclick="test">Click To Change Player's Color</button>
<script>
function Test() {
document.getElementsByClassName("class1").style.background = "yellow";
</script>
The onclick="test" does nothing - you may be confusing the structure element.onclick = test - which sets which function is run on the element being clicked - with the syntax for the onclick="test();" needed in the button element attributes.
A further error is that the function is called Test, not test. Javascript is case sensitive. Also you need to select the one element with class1, not retrieve a collection of such elements, so you can set its style (if that is useful, is it?).
I need help/advice on how to sort out an issue I have
https://raw.githubusercontent.com/TalvinJoshuaJacobs/TraceBall/master/src
My task is to code a game in Javascript and HTML where the user has to escape an enemy.
I am struggling with telling the the red box "obstacle" to follow me (the green box)
Any suggestions?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:20px solid #000000;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(130, 130, "green", 10, 120);
myObstacle = new component(130, 130, "red", 300, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1550;
this.canvas.height = 872;
this.canvas.style.cursor = "none";
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousemove', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
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 ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
myGamePiece.x = myGameArea.x;
myGamePiece.y = myGameArea.y;
}
myObstacle.x -= 5;
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
</script>
<p>Avoid hitting the obstacle, or else the game will stop.</p>
</body>
</html>
If you're looking for implementation suggestions, you should look into event sourcing. You could make your game piece an event emitter and trigger an event that will move your obstacle when the event is fired.
If you're using a bundler like webpack or something similar you can use the nodejs EventEmitter, but that's not available in the browser by default.
https://www.npmjs.com/package/EventEmitter
Check out this repo for a naive implementation of an event emitter that can be used in the browser: https://github.com/parallaxisjones/microevent.js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:20px solid #000000;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(130, 130, "green", 10, 120);
myObstacle = new component(130, 130, "red", 300, 120);
myGamePiece.on('move', function(params){
// do something with myObstacle
myObstacle.updatePosition(params);
})
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1550;
this.canvas.height = 872;
this.canvas.style.cursor = "none";
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousemove', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
//fire an event that can be subscribed to by other things
this.trigger('move', this)
}
this.crashWith = function(otherobj) {
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 ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
// register components as an event emitter with the microevent lib linked
MicroEvent.mixin(component)
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
myGamePiece.x = myGameArea.x;
myGamePiece.y = myGameArea.y;
}
myObstacle.x -= 5;
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
</script>
<p>Avoid hitting the obstacle, or else the game will stop.</p>
</body>
</html>
I have this little game in Javascript, It's sort of a rough replica of Flappy bird. It works well on desktops but on phones however, I can't seem to figure out which event handler to use with the button at the bottom to initiate the accelerate function.
When tried on phones, the button is clickable but there's no output.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 780;
this.canvas.height = 470;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
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() {
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.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
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 ((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])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
</body>
</html>
I am trying to make the divs "ySpeed(1)" and "ySpeed(-1)" make myGamePiece move up and down, and eventually, left to right. I made two functions called movePieceUp and movePieceDown. I do not know why the functions are not working correctly. Know a way I can make myGamePiece work correctly?
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 2;
this.speedY = 2;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.color = color;
this.update = function() {
random = Math.floor((Math.random() * 200) + 1);
random2 = Math.floor((Math.random() * 200) + 1);
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
randcolor = getRandomColor();
ctx = myGameArea.context;
if (this.type == "image") {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = randcolor;
ctx.fillRect(random, random2, 50, 50);
}
this.x = random;
this.y = random2;
this.width = 50;
this.height = 50;
this.color = randcolor;
}
}
function component2(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 2;
this.speedY = 2;
this.x = x;
this.y = y;
this.gravity = 2;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "image") {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.x = this.x + this.speedX;
this.y = this.y + this.speedY;
//removed hitting rock bottom because the background and other pieces will be off screen.
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
board = 1;
}
}
this.crashWith = function(otherobj) {
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 ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function startGame() {
random = Math.floor((Math.random() * 100) + 1);
random2 = Math.floor((Math.random() * 100) + 1);
square = new component(50, 50, "green", random, random2);
myGamePiece = new component2(30, 40, "greenhorn.gif", 220, 120);
enemyPiece2 = new component(50, 50, "Trump1.jpg", random, random2, );
myGameArea.start();
return square
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 450;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1000);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function updateGameArea() {
myGameArea.clear();
square.update();
myGamePiece.update();
enemyPiece2.update();
}
function movePieceUp() {
myGamePiece.ySpeed(1);
myGamePiece.speedY = 2;
}
function movePieceDown() {
myGamePiece.ySpeed(-1);
myGamePiece.speedX = 2;
}
document.getElementById("start").addEventListener('click', startGame);
document.getElementById("ySpeed(1)").addEventListener('click', movePieceUp);
document.getElementById("ySpeed(-1)").addEventListener('click', movePieceDown);
<p> Click Start Game to play </p>
<div id="start">Start Game</div>
<div id="hi">Hi</div>
<div id="ySpeed(1)">UP</div>
</p>
<div id="ySpeed(-1)">DOWN</div>
You need to be declaring your myGamePiece variable in a place that makes it accessibly by the functions using it. Either make it 'global' by declaring it outside and before the function calls, or pass the variable to the appropriate functions as a parameter.