I want to add a <button> to a canvas, and I thought adding it like this may work, but it doesn't!! How do you add a <button> element to innerHTML inside a canvas?
Earlier (in case this helps,):
ctx = myGameArea.context;
<script>
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
//this next part doesn't work!!!
ctx.innerHTML = ("<button onclick='startGame()'>Restart</button>");
}
}
</script>
For full code:
<!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 myObstacle;
var transitionBlock;
var blockTransition;
function startGame() {
myGamePiece = new component(40, 40, "#00ff00ff", 50, 140);
myObstacle = new component(80, 37, "#cf0000ff", 240, 0);
transitionBlock=new component(10, 80, "#f1f1f1ff", 590, 120);
blockTransition=new component(10, 80, "#f1f1f1ff", -40, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 560;
this.canvas.height = 320;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
}
}
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.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 {
myGamePiece.update();
myGameArea.clear();
myObstacle.update()
transitionBlock.update();
blockTransition.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
}
if (myGameArea.key && myGameArea.key == 37||myGameArea.key && myGameArea.key == 65) {myGamePiece.speedX = -3; } else if (myGameArea.key && myGameArea.key == 39||myGameArea.key && myGameArea.key == 68) {myGamePiece.speedX = 3; } else if (myGameArea.key && myGameArea.key == 38||myGameArea.key && myGameArea.key == 87) {myGamePiece.speedY = -3; } else if (myGameArea.key && myGameArea.key == 40||myGameArea.key && myGameArea.key == 83) {myGamePiece.speedY = 3; } else {myGamePiece.speedX = 0; myGamePiece.speedY = 0;}
myGamePiece.update();
}
</script>
</body>
</html>
HTML inside a canvas is not possible , however what you can do is to give your button an absolute position on the top of your canvas.
Here is a small example:
button{
position:absolute;
left:100px;
top:50px;
}
<!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 myObstacle;
var transitionBlock;
var blockTransition;
function startGame() {
myGamePiece = new component(40, 40, "#00ff00ff", 50, 140);
myObstacle = new component(80, 37, "#cf0000ff", 240, 0);
transitionBlock=new component(10, 80, "#f1f1f1ff", 590, 120);
blockTransition=new component(10, 80, "#f1f1f1ff", -40, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 560;
this.canvas.height = 320;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
}
}
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.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 {
myGamePiece.update();
myGameArea.clear();
myObstacle.update()
transitionBlock.update();
blockTransition.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
}
if (myGameArea.key && myGameArea.key == 37||myGameArea.key && myGameArea.key == 65) {myGamePiece.speedX = -3; } else if (myGameArea.key && myGameArea.key == 39||myGameArea.key && myGameArea.key == 68) {myGamePiece.speedX = 3; } else if (myGameArea.key && myGameArea.key == 38||myGameArea.key && myGameArea.key == 87) {myGamePiece.speedY = -3; } else if (myGameArea.key && myGameArea.key == 40||myGameArea.key && myGameArea.key == 83) {myGamePiece.speedY = 3; } else {myGamePiece.speedX = 0; myGamePiece.speedY = 0;}
myGamePiece.update();
}
</script>
<button>Hello I am a button floating on the top of the canvas</button>
</body>
</html>
As you can see in the example the button is floating over the canvas, but not inside it.
<div style="position: relative;">
<canvas style="width:300px; height: 300px;" />
<button style="position:absolute; top: 50%; left: 50%>hello</button>
</div>
Related
After the element or game-piece collides with the wall it stops moving. How can i reset the collision detection so that after the game-piece collides with the wall it is still able to move? Also after the game-piece collides with the ground it stops moving to. So how can i reset that collision detection so that it can move after colliding with the wall?
var myGamePiece;
var myObstacle;
var e = e || window.event;
var speed = 3;
var gravity = 0.05;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myObstacle = new component(10, 200, "green", 300, 120);
myGameArea.start();
myGameArea.gravityPhysics();
}
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.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
gravityPhysics: function() {
myGamePiece.speedY = -speed;
},
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.hitBottom();
};
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;
};
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if (
myGameArea.canvas.height - this.height &&
myGamePiece.key == 38
) {
this.y = this.speedY;
}
this.gravitySpeed = 0; // reset?
}
};
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y -= myGamePiece.speedY;
myGamePiece.update();
}
if (
myGameArea.gravityPhysics() &&
e.keyCode == document.addEventListener("keydown")
) {
myGamePiece.speedY = gravity - 10;
e.keyCode = true;
}
}
document.onkeydown = checkKeyD;
document.onkeyup = gravityPhysics;
function checkKeyD(e) {
if (e.keyCode == "38") {
// up arrow
myGamePiece.speedY = speed;
} else if (e.keyCode == "40") {
// down arrow
myGamePiece.speedY = -speed;
} else if (e.keyCode == "37") {
// left arrow
myGamePiece.speedX = -speed;
} else if (e.keyCode == "39") {
// right arrow
myGamePiece.speedX = speed;
}
}
if ((e = e || (window.event && window.event == false))) {
myGamePiece.speedY -= gravity;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
I need help finishing a function that shoots bullets after pressing 'space'.
I tried using these
var b = new bullet();
var bullets = []
bullets.push(b)
Then a for loop like this:
for (var i = 0; i < 6; i++) {
but I cant get it to work. Basically a function that every time a bullet is made, it is stored in an array then space loops through the array making new bullets on space press.
fiddle: https://jsfiddle.net/tmanrocks999/7mLpo8uj/652/
code:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullet;
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 0, 240);
endGoalPiece = new component(30, 30, "black", 450, 240);
myEnemy1 = new component(30, 30, "green", 200, 240);
}
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.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
//this.gravity = 0.05;
//this.gravitySpeed = 0;
this.x = x;
this.y = y;
this.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.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;
}
}
}
function jump() {
myGamePiece.gravitySpeed=-1;
}
}
function shootGun(){
bullet = new component(11, 5, "blue", myGamePiece.x+27 , myGamePiece.y+13 );
bullet.newPos();
bullet.speedX=1;
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }//left
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }//right
if (myGameArea.key && myGameArea.key == 38) {myGamePiece.gravitySpeed = -1; }//jump
if (myGameArea.key && myGameArea.key == 32) {shootGun()}//shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullet.newPos();
bullet.update();
}
</script>
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>
</body>
</html>
I expect on space press for bullets to keep being created by looping through the array but at the moment after space press only 1 bullet is made and position is reset every time you press space ( I know why this is I don't need it explained).
How can I get the illusion of a shooter.
Take a look at this code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>STACKOVERFLOW</title>
<style>
canvas {
border: 4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullets = [];
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 0, 240);
endGoalPiece = new component(30, 30, "black", 450, 240);
myEnemy1 = new component(30, 30, "green", 200, 240);
}
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.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
//this.gravity = 0.05;
//this.gravitySpeed = 0;
this.x = x;
this.y = y;
this.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.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;
}
}
function jump() {
myGamePiece.gravitySpeed = -1;
}
function shootGun() {
let bullet = new component(11, 5, "blue", myGamePiece.x + 27, myGamePiece.y + 13);
bullet.newPos();
bullet.speedX = 1;
bullets.push( bullet );
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
} //left
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
} //right
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.gravitySpeed = -1;
} //jump
if (myGameArea.key && myGameArea.key == 32) {
shootGun()
} //shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullets.forEach( (bullet)=> {
bullet.newPos()
bullet.update();
});
// bullet.newPos();
// bullet.update();
}
</script>
</body>
</html>
Codepen
I'm new to programming and I tried to make a game. You move a red block and when you hit a green block the you go back to (0,0) and the green block goes to a random location.
Now my question is how do I put a score counter in the game when I hit the green block that it counts +1.
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[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) {
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.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)) {
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
document.onkeydown = anim;
window.onload=startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<button onmousedown="anim(e)" onmouseup="clearmove()" ontouchstart="moveup()">Start</button>
<br><br>
<p>press start to start
<br> use the buttons ↑ ↓ → ← on your keyboard to move stop with the space</p>
Changes
Added an <output> tag to display score.
Redefined event handlers/listeners
Details on changes are commented in demo
Demo
// Reference output#score
var score = document.getElementById('score');
// Declare points
var points = 0;
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[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) {
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.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)) {
// Convert points to a real number
points = parseInt(points, 10);
// Increment points
points++;
// Set output#score value to points
score.value = points;
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
/* Set on click handler
|| When event occurs call startGame() / exclude
|| parenthesis
*/
document.onclick = startGame;
/* Register keydown event
|| When event occurs call anim() / exclude parenthesis
*/
document.addEventListener('keydown', anim, false);
/* When a callback is a named function / exclude the
|| parenthesis
*/
window.onload = startGame;
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
button {
font: inherit;
}
<br><br>
<button id='start'>Start</button>
<br><br>
<label for='score'>Score: </label>
<output id='score'>0</output>
<br><br>
<p>Click <kbd>Start</kbd> button</p>
<p>Use the buttons ↑ ↓ → ← on your keyboard to move stop with the spacebar.</p>
add
var chrashed = 0;
and use
if (myGamePiece.crashWith(myObstacle)) {
crashed++;
showCrashed;
return startGame();
}
https://jsfiddle.net/mplungjan/m4w3ahj1/
This question already has answers here:
Bing Maps API v8 - pushpin SVG URI image
(1 answer)
JavaScript Failed to execute 'drawImage'
(3 answers)
Uncaught TypeMismatchError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D'
(1 answer)
Failed to execute 'drawImage' on 'CanvasRenderingContext2D'
(1 answer)
Closed 5 years ago.
When trying to draw an image on an obstacle in an html canvas game I get this error message: Uncaught InvalidStateError: Failed to execute 'drawimage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The obstacle is invisible but the game still stops if the player collides with where it should be. The other stationary obstacles' images in the game are visible. What do I do?
I tried uploading the images in my html to let them load before using them but it still doesn't work. Other articles about similar situations do not cover this same context and do not help me who is quite new to programming.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"> <link/>
</head>
<body onload="startGame()">
<h2> My Lost Game </h2>
<p>Press the 'up', 'down', 'left' and 'right' keys on your keyboard to move. Avoid the obstacles and reach the goal.</p><br>
<p></p>
<script>
var myObstacle = [];
function startGame() {
myGameArea.start();
myGameGoal = new component(75, 95, "player2.jpg", 710, 215, "image");
myGamePiece = new component(75, 95, "player.jpg", 10, 215, "image");
myObstacle2 = new component (110, 150, "obstacle2.jpg", 350, 0, "image");
myObstacle3 = new component (110, 150, "obstacle3.jpg", 530, 350, "image");
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 800;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[4]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = true;
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = false;
})
},
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;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (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.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, y;
for (i = 0; i < myObstacle.length; i += 1) {
if (myGamePiece.crashWith(myObstacle[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = 200;
y = 300;
myObstacle.push(new component(110, 150, "obstacle1.jpg", x, y, "image"));
}
for (i = 0; i < myObstacle.length; i += 1) {
myObstacle[i].y += -1;
myObstacle[i].update();
}
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -3; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 3; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -3; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 3; }
myObstacle2.update();
myObstacle3.update();
myGameGoal.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
</script>
</body>
</html>
I am working on Browser game, and I wanted to make map where you can move around, fight with mobs, buy some stuff, but only map. Everything else will be in different pages.
So I made map with multiple images which are in loop.
It reads value world, x and y from database. I have made it work with ajax so the page doesnt refresh every time you move, but I wanted to make this map using Canvas.
$ystart = $y - 2;
$ymax = $y + 2;
$xstart = $x - 3;
$xmax = $x + 3;
for($y=$ystart;$y<=$ymax;$y++){
echo "<tr>";
for($x=$xstart;$x<=$xmax;$x++){
// echo "<td><img src=images/map/day/".$x."_".$y.".jpg width=100 height=100 border=0></td>\n";
if($x==$posx and $y==$posy){
echo "<td background=images/map/world_".$world."/".$y."_".$x.".jpg><img src=images/char.png width=100 height=100 border=0></td>";
} else{
echo "<td><img src=images/map/world_".$world."/".$y."_".$x.".jpg width=100 height=100 border=0></td>";
}
}
echo "</tr>";
}?>
I have done this so far
body {
margin: 0;
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload="startGame()">
<script>
var myGamePiece;
var myUpBtn;
var myDownBtn;
var myLeftBtn;
var myRightBtn;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myUpBtn = new component(30, 30, "blue", 50, 10);
myDownBtn = new component(30, 30, "blue", 50, 70);
myLeftBtn = new component(30, 30, "blue", 20, 40);
myRightBtn = new component(30, 30, "blue", 80, 40);
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.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousedown', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('mouseup', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
window.addEventListener('touchstart', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('touchend', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
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.clicked = function() {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var clicked = true;
if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
clicked = false;
}
return clicked;
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.x && myGameArea.y) {
if (myUpBtn.clicked()) {
myGamePiece.y -= 1;
}
if (myDownBtn.clicked()) {
myGamePiece.y += 1;
}
if (myLeftBtn.clicked()) {
myGamePiece.x += -1;
}
if (myRightBtn.clicked()) {
myGamePiece.x += 1;
}
}
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && (myGameArea.key == 37 || myGameArea.key == 65)) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && (myGameArea.key == 39 || myGameArea.key == 68)) {
myGamePiece.speedX = 1;
}
if (myGameArea.key && (myGameArea.key == 38 || myGameArea.key == 87)) {
myGamePiece.speedY = -1;
}
if (myGameArea.key && (myGameArea.key == 40 || myGameArea.key == 83)) {
myGamePiece.speedY = 1;
}
myGamePiece.newPos();
myUpBtn.update();
myDownBtn.update();
myLeftBtn.update();
myRightBtn.update();
myGamePiece.update();
}
</script>
</body>
But I can't figure out how to make this background loop in canvas based on x and y position and how to make it change when you move.
I'm trying to learn about canvas myself, so I've been browsing through these questions. I thought yours would be a fun exercise to try.
Basically, I'm creating an object, and moving it at each iteration. I will constantly check the x position of my object. And depending on its value, I can change the background image.
Try this and see for yourself. Try moving your right arrow key and then left arrow key. You will notice the background image changes.
var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
function hero(x, y) {
this.x = x;
this.y = y;
this.moveLeft = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x -= 5;
drawHero(this.x, this.y);
};
this.moveRight = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x += 5;
drawHero(this.x, this.y);
};
this.moveUp = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y -= 5;
drawHero(this.x, this.y);
}
this.moveDown = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y += 5;
drawHero(this.x, this.y);
}
}
function drawHero(x,y) {
ctx.fillStyle = "red";
ctx.fillRect(x, y, 10, 10);
}
var hero1 = new hero(40, 40);
ctx.fillStyle = "red";
ctx.fillRect(40, 40, 10, 10);
window.addEventListener("keydown", function(event) {
if (event.keyCode == 38) {
hero1.moveUp();
}
else if (event.keyCode == 37) {
hero1.moveLeft();
}
else if (event.keyCode == 39) {
hero1.moveRight();
}
else {
hero1.moveDown();
}
});
setInterval(function() {
if (hero1.x <= 100) {
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
}
else if (hero1.x > 100 && hero1.x <= 200) {
canvas.style.backgroundImage = "url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRi2F1v1PXpOEYScFCbvmsV-74C573z8tFBvIPXwDO8d1KImpJ09Q')";
}
else {
canvas.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSOSNoN1aLzWvpwrENvqPb4tKgzfeeqlMsUeC0fjdGABXXLdLIo')";
}
},50);
#my-canvas {
border: 1px solid black;
}
<canvas id="my-canvas" width="400" height="400"></canvas>