Uncaught syntax error : unexpected token function - javascript

I'm trying to learn javascript by creating a few classic arcade games and while testing my game, I received an Uncaught Syntax Error : unexpected token function from Chrome console and can't figure out how to debug it.
Here is the code concerned by the error :
function drawEverything() {
//Fills the screen
colorRect(0, 0, canvas.width, canvas.height, 'black');
if(showingLoseScreen) {
canvasContext.font = '16px Arial';
canvasContext.fillStyle = 'white';
canvasContext.fillText("You lost!", 395, 200);
canvasContext.fillText("Score :" + playerScore, 380, 300);
canvasContext.fillText("Total Score :" + totalScore, 380, 350);
canvasContext.fillText("click to reload game", 380, 400);
}
if(showingWinScreen) {
canvasContext.font = '16px Arial';
canvasContext.fillStyle = 'white';
canvasContext.fillText("You won!", 395, 200);
canvasContext.fillText("Total Score :" + totalScore, 380, 300);
canvasContext.fillText("click to advance to next level", 380, 400);
}
//Score
canvasContext.font = '16px Arial';
canvasContext.fillStyle = 'white';
canvasContext.fillText("Score: "+playerScore, 8, 20);
//Lives
canvasContext.font = "16px Arial";
canvasContext.fillStyle = "white";
canvasContext.fillText("Lives: "+playerLives, canvas.width-65, 20);
collisionDetection();
drawBricks();
//draws the paddle
colorRect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight, 'white');
//draws the ball
colorCircle(ballX, ballY, 10, 'white');
}
Here are the functions called within it :
function drawBricks() {
for (c=0; c < brickColumnCount; c++) {
colors = ['yellow', 'red', 'purple', 'maroon', 'green', 'gray', 'blue']
color = colors[Math.floor(Math.random()*colors.length)];
for(r=0; r < brickRowCount; r++) {
if(bricks[c][r].status == 1) {
var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop;
bricks[c][r].x = 0;
bricks[c][r].y = 0;
colorRect(brickX, brickY, brickWidth, brickHeight, color);
}
}
}
}
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
canvasContext.fill();
}
function colorRect(leftX, topY, width, height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX, topY, width, height);
}
Thanks for taking the time to read my code and providing an answer if you are able.
Louis

The problem is in this block
//Local functions//
//function handleMouseClick(evt) {
if(showingLoseScreen) {
gameReset();
} else if(showingWinScreen) {
playerScore = 0;
//level++
showingWinScreen = false;
} else if(showingFinalScreen) {
gameReset();
//}
You have a missing close bracket there, in the last else if. So you should close that block, no matter if you want to uncomment the function or not.
//Local functions//
//function handleMouseClick(evt) {
if(showingLoseScreen) {
gameReset();
} else if(showingWinScreen) {
playerScore = 0;
//level++
showingWinScreen = false;
} else if(showingFinalScreen) {
gameReset();
}
//}

Related

Animation assistance with a circle using JavaScript in a Canvas--what am I missing?

I'm trying to create simple animation to take the moon that I have drawn behind the clouds and allow users to move it across the x axis in the canvas. I have seen where others have done this with rectangles, and I have seen where their code seems basic enough for my inexperience to follow... but I'm struggling a bit with my code.
Every time I put code in that I think will work, it wipes out the canvas... which means I have placement and structural issues... but I'm having trouble figuring out where and how.
Can someone help me figure out how to animate my drawMoon so that it will move across the x axis when the left and right arrow keys are used?
NOTE I have tried using event listeners for keydown and keyup, but I'm sure I'm doing it wrong.
Attaching code that has nothing included so that you all have the base code without the animation attempt.
Any help is appreciated.
UPDATE I think I broke it more..... thoughts?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Howling at the Moon</title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="900" height="900">Your browser does not support the canvas tag.</canvas>
<script type="text/javascript">
var canvas, ctx;
var moonx = 0;
var moony = 0;
var moonAngle = 0;
var incrementX = 0;
function init() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
window.addEventListener("keydown", handleKeydown, false);
window.addEventListener("keyup", handleKeyup, false);
drawMonster(260, 260);
drawMoon(100, 100);
drawCloud(150, 175);
requestId = requestAnimationFrame(animationLoop);
function handleKeydown(evt) {
if (evt.keyCode === 37) {
incrementX = -1;
} else if (evt.keyCode === 39) {
incrementX = 1;
}
}
function handleKeyup(evt) {
incrementX = 0;
}
function animationLoop() {
context.globalCompositeOperation = 'destination-out'
}
drawMoon(moonx, moony, moonAngle, "green", "yellow");
moonx += incrementX;
requestId = requestAnimationFrame(animationLoop);
}
function drawMonster(x, y) {
ctx.save();
ctx.beginPath();
ctx.arc(740, 750, 175, 0, Math.PI / 0.5);
ctx.fillStyle = "lightgrey";
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
//mouth1
ctx.fillStyle = "black";
ctx.fillRect(x + 350, y + 550, 200, 20);
//mouth2
ctx.fillStyle = "black";
ctx.fillRect(x + 375, y + 540, 150, 20);
//mouth3
ctx.fillStyle = "black";
ctx.fillRect(x + 375, y + 560, 150, 20);
ctx.restore();
//eyes
addShadows2();
ctx.fillStyle = "lightslategrey";
ctx.fillRect(x + 350, y + 400, 40, 40);
ctx.fillRect(x + 450, y + 400, 40, 40);
//pupil
ctx.fillStyle = "black";
ctx.fillRect(x + 350, y + 400, 20, 20);
ctx.fillRect(x + 450, y + 400, 20, 20);
}
//moon
function drawMoon(moonx, moony) {
ctx.beginPath();
ctx.arc(100, 75, 150, 0, Math.PI / 0.5);
ctx.fillStyle = "lightgrey";
addShadows();
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
}
//cloud
function drawCloud(x, y) {
ctx.beginPath();
ctx.arc(x, y, 60, Math.PI * 0.5, Math.PI * 1.5);
ctx.arc(x + 70, y - 60, 70, Math.PI * 1, Math.PI * 1.85);
ctx.arc(x + 152, y - 45, 50, Math.PI * 1.37, Math.PI * 1.91);
ctx.arc(x + 200, y, 60, Math.PI * 1.5, Math.PI * 0.5);
ctx.moveTo(x + 200, y + 60);
ctx.lineTo(x, y + 60);
ctx.strokeStyle = "#797874";
ctx.stroke();
ctx.fillStyle = "lightslategrey";
ctx.fill();
}
function addShadows() {
ctx.shadowColor = "beige"; // color
ctx.shadowBlur = 160; // blur level
ctx.shadowOffsetX = 15; // horizontal offset
ctx.shadowOffsetY = 15; // vertical offset
}
function addShadows2() {
ctx.shadowColor = "black";
ctx.shadowBlur = 40;
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 10;
}
function addShadows3() {
ctx.shadowColor = "beige";
ctx.shadowBlur = 160;
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Howling at the Moon</title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="900" height="900">Your browser does not support the canvas tag.</canvas>
<script type="text/javascript">
var canvas, ctx;
function init() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
window.addEventListener('keydown', handleKeydown, false);
window.addEventListener('keyup', handleKeyup, false);
drawMonster(260, 260);
drawMoon(100, 100);
drawCloud(150, 175);
function handleKeydown(evt) {
if (evt.keyCode === 37) {
//left key
incrementX = -1;
} else if (evt.keyCode === 39) {
// right key
incrementX = 1;
}
}
function drawMonster(x, y) {
ctx.save();
ctx.beginPath();
ctx.arc(740, 750, 175, 0, Math.PI / .5);
ctx.fillStyle = "lightgrey";
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
//mouth1
ctx.fillStyle = 'black'
ctx.fillRect(x + 350, y + 550, 200, 20);
//mouth2
ctx.fillStyle = 'black'
ctx.fillRect(x + 375, y + 540, 150, 20);
//mouth3
ctx.fillStyle = 'black'
ctx.fillRect(x + 375, y + 560, 150, 20);
ctx.restore();
//eyes
addShadows2();
ctx.fillStyle = 'lightslategrey'
ctx.fillRect(x + 350, y + 400, 40, 40);
ctx.fillRect(x + 450, y + 400, 40, 40);
//pupil
ctx.fillStyle = 'black'
ctx.fillRect(x + 350, y + 400, 20, 20);
ctx.fillRect(x + 450, y + 400, 20, 20);
}
function animateMoon()
{
ctx.clearArc(0,0,canvas.width,canvas.height);
drawMoon(x,y);
requestId = requestAnimationFrame(animateMoon);
}
//moon
function drawMoon(x, y) {
ctx.beginPath();
ctx.arc(100, 75, 150, 0, Math.PI / .5);
ctx.fillStyle = "lightgrey";
addShadows();
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
}
//cloud
function drawCloud(x, y) {
ctx.beginPath();
ctx.arc(x, y, 60, Math.PI * 0.5, Math.PI * 1.5);
ctx.arc(x + 70, y - 60, 70, Math.PI * 1, Math.PI * 1.85);
ctx.arc(x + 152, y - 45, 50, Math.PI * 1.37, Math.PI * 1.91);
ctx.arc(x + 200, y, 60, Math.PI * 1.5, Math.PI * 0.5);
ctx.moveTo(x + 200, y + 60);
ctx.lineTo(x, y + 60);
ctx.strokeStyle = "#797874";
ctx.stroke();
ctx.fillStyle = "lightslategrey";
ctx.fill();
}
function addShadows() {
ctx.shadowColor = "beige"; // color
ctx.shadowBlur = 160; // blur level
ctx.shadowOffsetX = 15; // horizontal offset
ctx.shadowOffsetY = 15; // vertical offset
}
function addShadows2() {
ctx.shadowColor = "black";
ctx.shadowBlur = 40;
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 10;
}
function addShadows3() {
ctx.shadowColor = "beige";
ctx.shadowBlur = 160;
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
}
function start() {
// Start the animation loop, targets 60 frames/s
requestId = requestAnimationFrame(animationLoop);
}
function stop() {
if (requestId) {
cancelAnimationFrame(requestId);
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Howling at the Moon</title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="900" height="900">Your browser does not support the canvas tag.</canvas>
<script type="text/javascript">
var canvas, ctx;
function init() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
window.addEventListener('keydown', handleKeydown, false);
window.addEventListener('keyup', handleKeyup, false);
drawMonster(260, 260);
drawMoon(100, 100);
drawCloud(150, 175);
function handleKeydown(evt) {
if (evt.keyCode === 37) {
//left key
incrementX = -1;
} else if (evt.keyCode === 39) {
// right key
incrementX = 1;
}
}
function drawMonster(x, y) {
ctx.save();
ctx.beginPath();
ctx.arc(740, 750, 175, 0, Math.PI / .5);
ctx.fillStyle = "lightgrey";
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
//mouth1
ctx.fillStyle = 'black'
ctx.fillRect(x + 350, y + 550, 200, 20);
//mouth2
ctx.fillStyle = 'black'
ctx.fillRect(x + 375, y + 540, 150, 20);
//mouth3
ctx.fillStyle = 'black'
ctx.fillRect(x + 375, y + 560, 150, 20);
ctx.restore();
//eyes
addShadows2();
ctx.fillStyle = 'lightslategrey'
ctx.fillRect(x + 350, y + 400, 40, 40);
ctx.fillRect(x + 450, y + 400, 40, 40);
//pupil
ctx.fillStyle = 'black'
ctx.fillRect(x + 350, y + 400, 20, 20);
ctx.fillRect(x + 450, y + 400, 20, 20);
}
function animateMoon() {
ctx.clearArc(0, 0, canvas.width, canvas.height);
drawMoon(x, y);
requestId = requestAnimationFrame(animateMoon);
}
//moon
function drawMoon(x, y) {
ctx.beginPath();
ctx.arc(100, 75, 150, 0, Math.PI / .5);
ctx.fillStyle = "lightgrey";
addShadows();
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
}
//cloud
function drawCloud(x, y) {
ctx.beginPath();
ctx.arc(x, y, 60, Math.PI * 0.5, Math.PI * 1.5);
ctx.arc(x + 70, y - 60, 70, Math.PI * 1, Math.PI * 1.85);
ctx.arc(x + 152, y - 45, 50, Math.PI * 1.37, Math.PI * 1.91);
ctx.arc(x + 200, y, 60, Math.PI * 1.5, Math.PI * 0.5);
ctx.moveTo(x + 200, y + 60);
ctx.lineTo(x, y + 60);
ctx.strokeStyle = "#797874";
ctx.stroke();
ctx.fillStyle = "lightslategrey";
ctx.fill();
}
function addShadows() {
ctx.shadowColor = "beige"; // color
ctx.shadowBlur = 160; // blur level
ctx.shadowOffsetX = 15; // horizontal offset
ctx.shadowOffsetY = 15; // vertical offset
}
function addShadows2() {
ctx.shadowColor = "black";
ctx.shadowBlur = 40;
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 10;
}
function addShadows3() {
ctx.shadowColor = "beige";
ctx.shadowBlur = 160;
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
}
function start() {
// Start the animation loop, targets 60 frames/s
requestId = requestAnimationFrame(animationLoop);
}
function stop() {
if (requestId) {
cancelAnimationFrame(requestId);
}
}
</script>
</body>
</html>
There were several issues in your code and I'll share the changes I made to get the animation to work.
Errors
In your animationLoop, you referenced a variable named context which I believe you meant to reference ctx instead.
context.globalCompositeOperation = 'destination-out'
I can't say I've used this property of the CanvasRenderingContext2D, but I didn't notice any positive effects it produced for your code and the resulting animation. I first changed it to ctx.globalCompositeOperation and eventually removed it.
Another error was that you were declaring ctx and canvas in your init function even though you had variables declared outside the function. I opted to remove the declaration and just make it an assignment instead:
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
With these changes, the initial errors were resolved.
Issues
In init the shapes are drawn on the canvas and we have two identical lines using requestAnimationFrame:
requestId = requestAnimationFrame(animationLoop);
drawMoon(moonx, moony, moonAngle, "green", "yellow");
moonx += incrementX;
requestId = requestAnimationFrame(animationLoop);
I removed the first one (also removing the requestId assignment as it didn't seem necessary). Then, in order for the animationLoop to continue to animate, we need to call requestAnimationFrame(animationLoop) inside of the animationLoop function.
function animationLoop() {
// ...
requestAnimationFrame(animationLoop);
}
Then, in order to actually draw the shapes in each call of animationLoop, I moved the draw<shape> function calls inside of animationLoop. Also, we want to clear the canvas each time we draw on it to properly animate our shapes, so we'll need to use .clearRect. Now the animationLoop looks like this:
function animationLoop() {
moonx += incrementX;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMonster(260, 260);
drawCloud(150, 175);
drawMoon(moonx, moony, moonAngle, "green", "yellow");
requestAnimationFrame(animationLoop);
}
But the final reason the moon won't move when we press the left or right arrows is that we're not actually using the moonx and moony variables when drawing the moon. So, in drawMoon, instead of
ctx.arc(100, 75, 150, 0, Math.PI / .5);
this should be changed to the following
ctx.arc(moonx, moony, 150, 0, Math.PI / 0.5);
I believe I covered all of the major issues with your code to be able to draw all the shapes and move the moon with the left and right arrows. See the full code example below.
var canvas, ctx;
var moonx = 0;
var moony = 0;
var moonAngle = 0;
var incrementX = 0;
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
window.addEventListener("keydown", handleKeydown, false);
window.addEventListener("keyup", handleKeyup, false);
requestAnimationFrame(animationLoop);
function handleKeydown(evt) {
if (evt.keyCode === 37) {
incrementX = -1;
} else if (evt.keyCode === 39) {
incrementX = 1;
}
}
function handleKeyup(evt) {
incrementX = 0;
}
function animationLoop() {
moonx += incrementX;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMonster(260, 260);
drawCloud(150, 175);
drawMoon(moonx, moony, moonAngle, "green", "yellow");
requestAnimationFrame(animationLoop);
}
}
function drawMonster(x, y) {
ctx.save();
ctx.beginPath();
ctx.arc(740, 750, 175, 0, Math.PI / 0.5);
ctx.fillStyle = "lightgrey";
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
//mouth1
ctx.fillStyle = "black";
ctx.fillRect(x + 350, y + 550, 200, 20);
//mouth2
ctx.fillStyle = "black";
ctx.fillRect(x + 375, y + 540, 150, 20);
//mouth3
ctx.fillStyle = "black";
ctx.fillRect(x + 375, y + 560, 150, 20);
ctx.restore();
//eyes
addShadows2();
ctx.fillStyle = "lightslategrey";
ctx.fillRect(x + 350, y + 400, 40, 40);
ctx.fillRect(x + 450, y + 400, 40, 40);
//pupil
ctx.fillStyle = "black";
ctx.fillRect(x + 350, y + 400, 20, 20);
ctx.fillRect(x + 450, y + 400, 20, 20);
}
//moon
function drawMoon(moonx, moony) {
ctx.beginPath();
ctx.arc(moonx, moony, 150, 0, Math.PI / 0.5);
ctx.fillStyle = "lightgrey";
addShadows();
ctx.fill();
ctx.lineWidth = 3;
ctx.stroke();
}
//cloud
function drawCloud(x, y) {
ctx.beginPath();
ctx.arc(x, y, 60, Math.PI * 0.5, Math.PI * 1.5);
ctx.arc(x + 70, y - 60, 70, Math.PI * 1, Math.PI * 1.85);
ctx.arc(x + 152, y - 45, 50, Math.PI * 1.37, Math.PI * 1.91);
ctx.arc(x + 200, y, 60, Math.PI * 1.5, Math.PI * 0.5);
ctx.moveTo(x + 200, y + 60);
ctx.lineTo(x, y + 60);
ctx.strokeStyle = "#797874";
ctx.stroke();
ctx.fillStyle = "lightslategrey";
ctx.fill();
}
function addShadows() {
ctx.shadowColor = "beige"; // color
ctx.shadowBlur = 160; // blur level
ctx.shadowOffsetX = 15; // horizontal offset
ctx.shadowOffsetY = 15; // vertical offset
}
function addShadows2() {
ctx.shadowColor = "black";
ctx.shadowBlur = 40;
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = 10;
}
function addShadows3() {
ctx.shadowColor = "beige";
ctx.shadowBlur = 160;
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
}
init();
<canvas id="myCanvas" width="900" height="900">Your browser does not support the canvas tag.</canvas>

<canvas> javascript for when touching another object

I'm making a website for my digital assessment for school & need a hand with my javascript game which is being coded inside the <canvas> element. So pretty much I've got this little drone being controlled by the "forward", "left" , "right" & "back" buttons to move the drone around, since my background is a flat 2d image with walls on it I've made 100% transparent boxes and placed them over the wall areas to mimic the walls being there.
I just can't find any help with the IF statement where the drone touches the invisible box it puts it back to 43X 110Y... the code is below if you think you can help!! :)
(MyGamePiece is the drone, myHitBox is the invisible image.)
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myBackground;
var myHitBox;
var myHitBox1;
var myHitBox2;
var myHitBox3;
var myHitBox4;
var myHitBox5;
function startGame() {
myGamePiece = new component(50, 50, "img/forward.gif", 43, 110, "image");
myHitBox = new component(275, 20, "img/hitbox.png", 250, 169, "image");
myHitBox1 = new component(30, 100, "img/hitbox.png", 250, 170, "image");
myHitBox2 = new component(280, 25, "img/hitbox.png", 0, 80, "image");
myHitBox3 = new component(30, 100, "img/hitbox.png", 120, 80, "image");
myHitBox4 = new component(145, 25, "img/hitbox.png", 375, 80, "image");
myHitBox5 = new component(30, 100, "img/hitbox.png", 375, 0, "image");
myBackground = new component(650, 270, "img/MAP.jpg", 0, 0, "image");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 650;
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;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
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 (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;
}
}
function updateGameArea() {
myGameArea.clear();
myBackground.newPos();
myBackground.update();
myGamePiece.newPos();
myGamePiece.update();
myHitBox.newPos();
myHitBox.update();
myHitBox1.newPos();
myHitBox1.update();
myHitBox2.newPos();
myHitBox2.update();
myHitBox3.newPos();
myHitBox3.update();
myHitBox4.newPos();
myHitBox4.update();
myHitBox5.newPos();
myHitBox5.update();
}
function move(dir1) {
if (dir1 == "down") {myGamePiece.speedY = 5; myGamePiece.image.src = "img/forward.gif";}
else if (dir1 == "up") {myGamePiece.speedY = -5; myGamePiece.image.src = "img/back.gif";}
else if (dir1 == "right") {myGamePiece.speedX = 5; myGamePiece.image.src = "img/right.gif";}
else if (dir1 == "left") {myGamePiece.speedX = -5; myGamePiece.image.src = "img/left.gif";}
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
</script>
<div style="text-align:center;width:480px;">
<button onmousedown="move('up')" onmouseup="clearmove()" ontouchstart="move('up')">UP</button><br><br>
<button onmousedown="move('left')" onmouseup="clearmove()" ontouchstart="move('left')">LEFT</button>
<button onmousedown="move('right')" onmouseup="clearmove()" ontouchstart="move('right')">RIGHT</button><br><br>
<button onmousedown="move('down')" onmouseup="clearmove()" ontouchstart="move('down')">DOWN</button>
</div>
The alternative solution I mentioned in the comments, as you were interested:
If you have a complex background, you can create a simple map equivalent.
E.g. This background:
Would use this simple layout map:
Then have a second invisible canvas where you run something along these lines:
(Rough outline, will need to be edited to work for you)
var x = <drone X position>;
var y = <drone Y position>;
var colour = secondCanvasContext.getImageData(x, y, 1, 1).data;
if(colour[0] == 0 && colour[1] == 0 && colour[2] == 0){
// Your drone is on a black background, so it's not hitting a wall
}

Rectangle not appearing in js canvas

I have a devastating problem that I can't fix.
The JS canvas is screwing up a rectangle next to a player function expression.Here is the player code:
var menuSwitch = 0;
var pocx = 210;
var pocy = 20;
var switch1;
var lvlSwitch = 1;
var spd = 10;
var mx,my;
var pl = pl();
function pl(){
return{
draw: function(){
//draw the player
ctx.clearRect(0,0,w,h);//clears so the player doesn't "drag"
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(pocx, pocy, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
//move the player
if(switch1 == 0){
pocx = 210;
pocy = 20;
}else if(switch1 == 1){
pocy -= spd;
}else if(switch1 == 2){
pocx -= spd;
}else if(switch1 == 3){
pocy += spd;
}else if(switch1 == 4){
pocx += spd;
}
//rect bounding the player
if(pocx < 5){//since half of the diameter of the player is 5, the edge of the circle "bounces"
switch1 = 4;
}
if(pocy < 5){
switch1 = 3;
}
if(pocx > w){
switch1 = 2;
}
if(pocy > h){
switch1 = 1;
}
}
};
}
The canvas is 420 by 420. The paint() function, which goes 30 milliseconds each time by a setInterval is displayed here:
function paint(){
//pl.draw();
if(menuSwitch == 0){
ctx.fillStyle = 'black';
ctx.fillRect(0,0,w,h);
ctx.fillStyle = 'skyblue';
ctx.fillRect(20,20,380,50);
ctx.font = 'normal 30pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Math Path",105,60);
ctx.fillStyle = 'skyblue';
ctx.fillRect(105,150,210,25);//105+210=315
ctx.font = 'normal 15pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Start",170,170);
}
if(menuSwitch == 1){
ctx.fillStyle = 'blue';
ctx.fillRect(300,20,120,20);
pl.draw();
}
}
However, I'm focusing on the place where menuSwitch == 1 in the if statement. You can see that I'm calling the player. The player shows up, but not the rectangle. Please help? :(
Useful link: Canvas Tutorial
Html code if you need it:
Jsfiddle
It is because you call ctx.fillRect(300,20,120,20); in the player function. Fo fix it, remove that line and add it to your paint function like:
function paint() {
ctx.clearRect(0, 0, w, h); //clears so the player doesn't "drag"
//pl.draw();
if (menuSwitch == 0) {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = 'skyblue';
ctx.fillRect(20, 20, 380, 50);
ctx.font = 'normal 30pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Math Path", 105, 60);
ctx.fillStyle = 'skyblue';
ctx.fillRect(105, 150, 210, 25); //105+210=315
ctx.font = 'normal 15pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Start", 170, 170);
}
if (menuSwitch == 1) {
ctx.fillStyle = 'blue';
pl.draw();
ctx.fillRect(300, 20, 120, 20);
}
}
Fiddle showing example: https://jsfiddle.net/22w9j3p0/

Javascript function getting called multiple times

This is a game i am making. I am getting a very wiered error. When i click on first tile i am calling afunction level3. Which draws few vertical lines. After that even clearing the canvas my level2 is being executed.
Need Help !
You dont have to look entire code. Just the level2 and level 3 function.Check Demo link.When you click on first tile "Trader" level3 is called but remains for a short time and again level2 is executing without even calling.
SOLVED
Fixed Demo :http://stndlkr200.github.io/bugfixed.html
Bug Demo : http://stndlkr200.github.io/testbug.html
<html>
<head>
<style>
*{
background-color: black;
}
canvas{display: block;}
</style>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
window.onload=function() {
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var w=window.innerWidth;
canvas.width=w;
var h=window.innerHeight;
canvas.height=h;
var ctr=0;
var words=["We Need Swaraj","Play for Change","Aam Aadmi Party","5 saal Kejriwal","AAP for
Change","Vote for Good","Arvind Kejriwal","Kejriwal Fir Se","We Need Swaraj","Play for
Change","Aam Aadmi Party","5 saal Kejriwal","AAP for Change","Vote for Good","Arvind
Kejriwal","Kejriwal Fir Se","We Need Swaraj","Play for Change","Aam Aadmi Party","5 saal
Kejriwal","AAP for Change","Vote for Good","Arvind Kejriwal","Kejriwal Fir Se","We Need
Swaraj","Play for Change","Aam Aadmi Party","5 saal Kejriwal","AAP for Change","Vote for
Good","Arvind Kejriwal","Kejriwal Fir Se"];
var j=0;
function box(x,y){
this.x=x;
this.y=y;
this.xVelo=10+Math.random()*20;
this.yVelo=1;
this.width=500;
this.height=500;
this.r=Math.round(Math.random()*255);
this.g=Math.round(Math.random()*255);
this.b=Math.round(Math.random()*255);
this.rgba = "rgba("+this.r+","+this.g+","+this.b+",1)";
this.message=words[i];
i++;
this.draw = function()
{
ctx.strokeStyle = this.rgba;
ctx.strokeRect(this.x,this.y,this.width,this.height);
ctx.font = 'bold 50px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle =this.rgba;
ctx.fillText(this.message, this.x+this.width/2, this.y+this.height/2);
ctr++;
if(ctr>7000){
clearInterval(timer1);
ctx.font = 'bold 50px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("Vote For Honest Leaders", 400, 400);
ctx.fillText("Vote For Kejriwal", 600, 30);
ctx.fillText("Vote For Delhi", 1000, 400);
ctx.strokeStyle="rgba(200,56,78,0.4)";
ctx.strokeRect(550,200,100,60);
ctx.font = 'bold 20px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="green";
ctx.fillText("Lets Play !", 600, 230);
}
this.update();
}
this.update = function()
{
if(this.x < 0) {
this.x = 0;
this.xVelo *= -1;
}
if(this.x > w - this.width)
{
this.x = w - this.width;
this.xVelo *= -5;
}
if(this.y < 0) {
this.y = 0;
this.yVelo *= -1;
}
if(this.y < h - this.height)
this.yVelo += .25;
if(this.y > h - this.height)
{
//this.xVelo *= .5
this.yVelo *= .5
this.y = h - this.height;
this.yVelo *= -2;
}
this.x += this.xVelo/5;
this.y += this.yVelo/3;
}
}
var boxes = [];
function draw()
{
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(0,0,0,0.5)"
ctx.fillRect(0,0,w,h);
ctx.globalCompositeOperation = "lighter"
for(i=0; i < boxes.length; i++)
boxes[i].draw();
update();
}
function update()
{
for(i=0; i < boxes.length; i++)
boxes[i].update();
}
var timer1= setInterval(function(){
boxes.push( new box(0,0))
},1000);
var timer= setInterval(draw,30);
canvas.addEventListener("click",play_function);
function play_function(e){
button_x=e.pageX;
button_y=e.pageY;
if(button_x<650 && button_x>500 && button_y<260 && button_y >200)
start_levels();
}
function start_levels(){
clearInterval(timer);
canvas.removeEventListener('click',play_function);
level1();
}
var level1=function(){
ctx.clearRect(0,0,w,h);
ctx.font = '13px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("MufflerMan wants you to sketch something.. Please do",500,10);
var dots=[];
var dotXval=["500","250","150","720","850"];
var dotYval=["100","250","300","250","300"];
function dot(xcod,ycod,radius,value){
this.xcod=xcod;
this.ycod=ycod;
this.radius=radius;
this.val=value;
}
function create_dots(x,y,radius,value){
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI,true);
ctx.fillStyle="white";
ctx.fill();
ctx.font = '10px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText(value,x-10,y-10);
}
function startLevel(){
var dotRadius=10;
var dotsCount=5;
for (var i = 0; i <dotsCount; i++){
dots.push(new dot(dotXval[i],dotYval[i],dotRadius,i+1));
}
for (var j=0; j<dots.length; j++) {
create_dots(dots[j].xcod, dots[j].ycod,5,dots[j].val);
}
}
startLevel();
var mouse={x:0,y:0};
var drag4sketch=function(e){
mouse.x=e.pageX-this.offsetLeft;
mouse.y=e.pageY-this.offsetTop;
}
canvas.addEventListener('mousemove',drag4sketch);
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
canvas.addEventListener('mousedown',function(e){
ctx.beginPath();
ctx.moveTo(mouse.x,mouse.y);
canvas.addEventListener('mousemove',sketch,false);
},false);
canvas.addEventListener('mouseup',function(){
canvas.removeEventListener('mousemove',sketch,false);
},false);
var sketch=function(){
ctx.lineTo(mouse.x,mouse.y);
ctx.stroke();
}
var time=0;
var clock=function(){
ctx.clearRect(1000,20,1200,200);
ctx.font = '20px Arial';
ctx.fillStyle ="white";
ctx.fillText(time++ + ' sec',1120,30);
if(time>2){
ctx.clearRect(0,0,w,h);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mouseup',level1);
canvas.removeEventListener('mousedown',level1);
canvas.removeEventListener('mousemove',level1);
canvas.removeEventListener('mouseup',sketch);
canvas.removeEventListener('mousedown',sketch);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mousemove',drag4sketch);
level2();
}
}
setInterval(clock,1000);
clearInterval(clock);
}
function level2(){
var m={x:0,y:0};
var rect_cordsX=["100","300","500","700","900","1100"];
var rect_cordsY=["50","160","370","480"];
var hints=
["Trader","Businessman","Student","Teacher","Writer","Scientist","Politicion","MufflerMan","Auto
Driver","Police","Doctor","Industrialist","Soldier","Musician","Cobbler","Social
Worker","MufflerMan","Engineer","Advocate","Reporter","Editor","MufflerMan","Poet","Actor"];
ctx.font = 'bold 13px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("MufflerMan wants you to find his companions..Your Luck! ",620,10);
var hint_cards=[];
var hint_card=function(x,y,hint){
this.x=x;
this.y=y;
this.hint=hint;
}
for (var i = 0; i< rect_cordsX.length; i++) {
for (var j=0;j<rect_cordsY.length;j++){
hint_cards.push(new hint_card(rect_cordsX[i],rect_cordsY[j],hints[i*j]));
}
}
for (var k=0;k<hint_cards.length;k++){
ctx.strokeStyle="white";
ctx.strokeRect(hint_cards[k].x,hint_cards[k].y,100,80);
ctx.font = 'bold 15px Calibri';
ctx.textAlign="center";
ctx.textBaseline="middle";
ctx.fillStyle="white";
ctx.fillText(hints[k],parseInt(hint_cards[k].x)+50,parseInt(hint_cards[k].y)+40);
}
function click_hint_card(e){
m.x=e.pageX-this.offsetLeft;
m.y=e.pageY-this.offsetTop;
if(m.x>100 && m.y>50 && m.x<200 && m.y<130){
console.log("Trader");
level3();
}
}
canvas.addEventListener('click',click_hint_card);
}
function level3 (){
ctx.clearRect(0,0,w,h);
ctx.beginPath();
for(var x=100;x<1200;x+=100){
ctx.moveTo(x,100);
ctx.lineTo(x,200);
ctx.moveTo(x,300);
ctx.lineTo(x,500);
}
ctx.strokeStyle="white";
ctx.stroke();
}
}
</script>
</body>
</head>
</html>
Your setInterval(clock, 1000); calls a block of code:
var clock=function(){
ctx.clearRect(1000,20,1200,200);
ctx.font = '20px Arial';
ctx.fillStyle ="white";
ctx.fillText(time++ + ' sec',1120,30);
if(time>2){
ctx.clearRect(0,0,w,h);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mouseup',level1);
canvas.removeEventListener('mousedown',level1);
canvas.removeEventListener('mousemove',level1);
canvas.removeEventListener('mouseup',sketch);
canvas.removeEventListener('mousedown',sketch);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mousemove',drag4sketch);
level2();
}
}
I suspect it is the last line of that clock function that is causing your problem. Remove it and it should go away.

Moving group of objects at the same time in canvas

My problem is that I have no idea how to implement group of objects, in my situation, group of rectangles moving all at the same time. Well, I implemented easily moving one rectangle with specific direction which you can see below from my code. Also I tried to add an array with group of rectangles. So again my question is how to implement group of rectangles (3 rows 3 columns, 9 of them, for instance) to move the same way how my one rectangle is moving in the code below????? So basically very right side of group and very left side of the group will hit the border while column in the middle of 3X3 will stay moving between two columns of 3X3.....Any help will appreciated. Thank you...
<html>
<head>
<title>Spaceman Invaders</title>
<script>
window.onload = function() {
var canvas = document.getElementById("screen");
context = canvas.getContext("2d");
context.fillStyle="black";
context.fillRect(0,0,canvas.width, canvas.height);
context.fillStyle = "red";
context.fillRect(30, 100, 20 , 20);
var posx = 27;
var posy = 100;
var go_right = true;
var go_down = false;
if (canvas.getContext) {
/* var array = [];
array.push(new Shape(20, 0, 50, 50, "red"));
array.push(new Shape(20, 60, 50, 50, "red"));
array.push(new Shape(20, 120, 50, 50, "red"));
array.push(new Shape(80, 0, 50, 50, "red"));
array.push(new Shape(80, 60, 50, 50, "red"));
array.push(new Shape(80, 120, 50, 50, "red"));
array.push(new Shape(140, 0, 50, 50, "red"));
array.push(new Shape(140, 60, 50, 50, "red"));
array.push(new Shape(140, 120, 50, 50, "red"));*/
setInterval( function() {
if (!go_down) {
if(posx < 250 && go_right) {
posx += 3;
} else if(posx < 30) {
go_right = true;
go_down = true;
} else if(!go_right) {
posx -= 3;
}else {
go_right = false;
go_down = true;
}
} else {
//if(posy <= 30)
posy += 5;
go_down = false;
}
context.fillStyle="black";
context.fillRect(0,0,canvas.width, canvas.height);
context.fillStyle = "red";
context.beginPath();
context.fillRect(posx, posy, 20 , 20);
context.fill();
}
, 20);
}
</script>
</head>
<body>
<canvas id="screen" width="300" height="500"/>
</body>
</html>
You will have to store the x,y position of each rectangle. You may create an new class for this. I've made you an example:
var Alien = function(x, y) {
this.x = x;
this.y = y;
this.posx = 30 + x*30;
this.posy = 90 + y*30;
this.go_right = true;
this.go_down = false;
this.perrow = 3;
}
Alien.prototype.move = function() {
if (!this.go_down) {
if(this.posx + (this.perrow-1-this.x) * 30 < 250 && this.go_right) {
this.posx += 3;
} else if(this.posx < 30 + this.x*30) {
this.go_right = true;
this.go_down = true;
} else if(!this.go_right) {
this.posx -= 3;
} else {
this.go_right = false;
this.go_down = true;
}
} else {
//if(posy <= 30)
this.posy += 30;
this.go_down = false;
}
}
Alien.prototype.draw = function(context) {
if(this.x == 0) {
context.fillStyle = "red";
} else if(this.x == 1) {
context.fillStyle = "yellow";
} else {
context.fillStyle = "blue";
}
context.beginPath();
context.fillRect(this.posx, this.posy, 20 , 20);
context.fill();
}
Then you can update the position and draw each object separately in a loop inside of your intervall callback.
EDIT:
Now the objects move downwards all at once.
You can test it here:
http://jsfiddle.net/Z6F4d/3/

Categories