I am trying to program a game in html and javascript, for this I decided to use a canvas, as it will make the development easier. However, when I try to implement another object into the canvas, the code seems to break, I have been fiddling with the code, in order to see the issue, however, I have had no success so far. The code can be found below:
<!DOCTYPE html>
<html>
<head>
<Title>Game Prototype 1</Title>
</head>
<body onload= "startGame()">
<canvas id="canvas"
style =
"border:1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 65px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
<script>
var character;
function startGame(){
gameArea.start();
character = new character(30, 30, "red", 10, 120);
}
var gameArea = {
canvas:
document.getElementById("canvas");
start : function() {
this.canvas.width = 1000;
this.canvas.height = 800;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
}
function character(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
}
</script>
</body>
</html>
The output of the code is this:
At this point I am no longer sure whether the issue is which the character variable, and hence the character is not being displayed, or with the canvas, as the canvas has incorrect dimensions, I am not entirely sure why the canvas changes the dimensions (if the rectangle displayed on the screen is the canvas). This is what I mean by the code breaking.
You have some syntax errors in the gameArea object. (A } was missing, and in Javascript you use , instead of ; to separate members within an object.)
I recommend using the browser console to spot such issues. Here is your code with the object fixed:
<!DOCTYPE html>
<html>
<head>
<Title>Game Prototype 1</Title>
</head>
<body onload= "startGame()">
<canvas id="canvas"
style =
"border:1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 65px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
<script>
var character;
function startGame(){
gameArea.start();
character = new character(30, 30, "red", 10, 120);
}
var gameArea = {
canvas: document.getElementById("canvas"),
start: function() {
this.canvas.width = 1000;
this.canvas.height = 800;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
}
}
function character(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
}
</script>
</body>
</html>
Did this solve your problem or were you expecting something else to happen?
Related
I'm trying to write something that makes the different iterations of the cantor set. I copied and deleted some of my code and I don't understand why I am getting this undefined error.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
}
</style>
</head>
<body onload="startGame()">
<script>
//var n=10;
function startGame() {
sheet.start();
}
var sheet = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 726;
this.canvas.height = 680;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
ctx = sheet.context;
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();
</script>
</body>
</html>
But I had an example of some code very similar that it won't let me post because it says its mostly code. But some help would be appreciated because this ctx undefined is an error I get a lot and I'm not really sure what it means. I've always used it to draw things on the canvas and never concerned myself with learning what it meant.
Short answer
ctx is undefined because the object sheet doesn't have a property called context.
Thus ctx = sheet.context; will fail.
A bit longer answer
With
var sheet = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 726;
this.canvas.height = 680;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
you're declaring an object with two properties: canvas and start. As soon as you invoke the start() function on the object, it tries to set the width of it's canvas property to 726 - problem is, sheet doesn't call it's own property canvas before so document.createElement("canvas") won't ever execute.
The fix is simple: set canvas to undefined initially and create the actual canvas element inside the start function. Nevertheless you still won't have a context property so add it to the sheet object too.
Here's an example:
var sheet = {
canvas: undefined,
context: undefined,
start: function() {
this.canvas = document.createElement("canvas");
this.canvas.width = 200;
this.canvas.height = 200;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
sheet.start();
var ctx = sheet.context;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
I am new to Javascript and I am trying to create flappy bird in normal Javascript. I was following a tutorial and when I got to this point my code wasn't working and wasn't displaying the character (a yellow square) as it is apparently meant to be doing according to the tutorial. I was hoping that someone would be able to help me with my issue, thanks a lot.
This is my HTML code here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flappy Bird</title>
<style>
canvas {
border: 3px solid #000000;
display: block;
margin: 0 auto;
background-color: lightblue;
}
</style>
</head>
<body>
<canvas id="canvas" width="320" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
This is my Javascript code here:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.w = 40;
this.h = 40;
this.ySpeed = 3;
}
show() {
ctx.fillStyle = "yellow";
ctx.fillRect(this.x, this.y, this.w, this.h);
}
update() {
this.y += this.ySpeed;
this.ySpeed += gravity;
}
}
var p;
var gravity = 0.1;
window.onload = function () {
start();
setInterval(update, 10);
};
function start() {
p = new Player(400, 400);
}
function update() {
canvas.width = canvas.width;
//player
p.show();
p.update();
}
The size of your canvas is only 320px, but you are trying to draw a square at a position of 400px.
Try:
p = new Player(0, 400)
It works
The player is being drawn offscreen: the x coordinate for player (as well as the y coordinate) is 400, while the canvas is only 320 wide. I'd recommend you check the line p = new Player(400, 400) to ensure the numbers are correct.
Hey guy's I'm making a snake game in JS and right now all I'm trying to do is draw a snake in the center of the canvas. I've set the canvas dimensions to the board dimensions so everything scales right but nothing shows up. Any help would be appreciated:)
//declare global variables
const canvas = document.querySelector('#canvas');
//set canvas context
const ctx = canvas.getContext('2d');
//set canvas dimensions to board dimensions
canvas.width = 768;
canvas.height = 512;
//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;
//create snake unit
const unit = 16;
//create snake and set starting position
let snake = [{
x : cvsW/2,
y : cvsH/2
}]
ctx.fillStyle = 'limegreen';
ctx.fillRect(snake.x, snake.y, unit, unit);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake</title>
<style>
body {
background-color: #333;
}
#canvas {
background-color: #4d4d4d;
display: block;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<canvas id="canvas" width="768" height="512"></canvas>
<script src="script.js"></script>
</body>
</html>
This is happening because your snake is an array of objects. You either need to turn this into a single object for your code to work or use an index to select the object inside.
ctx.fillRect(snake[0].x-unit/2, snake[0].y-unit/2, unit, unit);
Also, note that in order to correctly centre your snake you need to subtract the unit/2 from both x and y coordinates.
You can also remove the setting of the canvas dimensions within your code, as this is set when your define the height and width attributes on your canvas element.
See working example below:
//declare global variables
const canvas = document.querySelector('#canvas');
//set canvas context
const ctx = canvas.getContext('2d');
//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;
//create snake unit
const unit = 16;
//create snake and set starting position
let snake = [{
x: cvsW / 2,
y: cvsH / 2
}];
ctx.fillStyle = 'lime';
ctx.fillRect(snake[0].x - unit / 2, snake[0].y - unit / 2, unit, unit);
body {
background-color: #333;
}
#canvas {
background-color: #4d4d4d;
display: block;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
<canvas id="canvas" width="768" height="512"></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>
<canvas id="GameArea"></canvas>
<script>
var myGamePiece;
myGamePiece = new component(30, 30, "red", 10, 120);
function component(width, height, color, x, y) {
console.log("component called");
this.width = width;
this.height = height;
this.x = x;
this.y = y;
var myGameArea=document.getElementById("startGame");
console.log("myGameArea");
var ctx = myGameArea.getContext("2d");
console.log("crossed");
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
</script>
<p>We have added a component to our game, a red square!</p>
</body>
</html>
//not able to getout of my error
in the above code i tried to create a rectangle on calling some function named component.
it created a rectangle by context but i am getting a error
Your canvas has an id of "GameArea", but you're trying to do getElementById("startGame").
Your canvas element id is "GameArea" but you refer in code as "startGame". That is why it is null
I have a canvas that I have in html that is supposed to be 25% of the page. I made a variable named width in javascript, and put it's value as 25%. When I make a context.clearRect(); with the width variable as the width parameter, it doesn't fix it what I was trying to do (which I have done tons of times) which is when the player rectangle moves, the clearRect keeps the background circulating so the rectangle isn't drawing (leaving a mark). Here is my width variable:
var width = 25%;
Here is my clearRect();
context.clearRect(0, 0, width, height);
Edit: I guess I will also post my whole entire code, to be easier.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25)), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
You need to use something like this:
context.clearRect(0, 0, (canvas.width * 0.25), height);
Try this?
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
// var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
</body>
</html>
Not sure what you actually wanted to ask yet your code has two syntax errors - thus it does not execute correctly:
var keys = [];
var speed = 4;
//var width = 25%; //This is no valid assignment and the value is not used..
var height = 400;
and
function render() {
//context.clearRect(0, 0, (canvas.width * 0.25)), height); //One bracket too much, can skip both tho..
context.clearRect(0, 0, canvas.width * 0.25, height);
You need to put your canvas in a container, and set up the container the way you want, then you make your canvas 100% of the containers properties using
clientHeight
and
clientWidth
JSFiddle: https://jsfiddle.net/53n2s0s9/