e.keyCode doesn't work - javascript

I'm new at programming and I do whatever I see in the youtube video to create a game with canvas. This code works in the video but doesn't work for me.I don't see key codes on the screen so key code thing doesn't work . I don't know what is wrong with the coding..
My codes:
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys[];
window.addEventListener("keydown", function(e) {
alert(e.keyCode);
}, false);
<html>
<head>
<title>GAME</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<canvas id="mainCanvas" width="500" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>

Always, when developing, do it with an open console. You're receiving the following error: Uncaught SyntaxError: Unexpected token [.
That's because you don't create arrays in JS like that. You actually do: var arr = [];. Just change var keys[] to var keys = [];

jsFiddle : https://jsfiddle.net/02f6nyh9/
javascript
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = new Array();
// var keys = []; // Either of these work
window.addEventListener("keydown", function(e) {
alert(e.keyCode);
}, false);
context.fillRect(0,0,500,400);
You just need to create an array correctly then it works fine :)

Related

Javascript HTML play sound only once, but more strange thing happened

I tried this simple snippet in codepen. and function once1 can play as many times as you want while once2 can play sound only once.
Anyone know what's the difference?
var simple = new
Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new
Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1(){
birdSound.play();
};
function once2(){
simple.play();
};
Here you go, I saw the other answer still wasn't working on jsfiddle or codepen so try this!
var simple = new
Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new
Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1(){
birdSound.load();
birdSound.play();
};
function once2(){
simple.load();
simple.play();
};
Just use .load :D
Update: Using the load() method, as suggested by the other poster, I can get the code below to repeatedly play the second sound in Chrome, but it still sounds different than it does in Firefox. In Firefox the sound plays smoothly, but in Chrome the sound ends more abruptly, with a little bit of a crackle or click. I suspect that there's just something about this particular sound file that isn't fully compatible with Chrome.
I'm able to get both sounds to play as many times as I want in Firefox with this Plunker here, but not in Chrome: http://plnkr.co/edit/gM8lobVoQoAtVSlwVZNC?p=preview
function init() {
var simple = new Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1() {
birdSound.play();
}
function once2() {
simple.load();
simple.play();
}
var btn1 = document.getElementById("one");
btn1.addEventListener('click', once1);
var btn2 = document.getElementById("two");
btn2.addEventListener('click', once2);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body onload="init()">
<button id="one">Sound 1</button><br>
<button id="two">Sound 2</button>
</body>
</html>
Which web browser were you using?

Weird error for use of keyCode should be working

I'm getting an error with my event.keyCode saying that
Cannot read property 'keyCode'
I want the code to when I press "I" to load the screen that I have drawn onto my canvas
var canvas = document.querySelector("canvas");
document.addEventListener('keydown', loadScreen);
canvas.width=640;
canvas.height=640;
var draw = canvas.getContext("2d");
loadScreen();
function loadScreen(event) {
var key = (event.keyCode);
if(key == 73)
{
InventoryScreen();
}
}
function InventoryScreen()
{
draw.fillStyle = "#D3D3D3";
draw.fillRect(50,50,100,80);
draw.fillRect(50,135,100,80);
draw.fillRect(50,220,100,80);
draw.fillRect(50,305,100,80);
draw.fillRect(50,390,100,80);
draw.fillRect(50,475,100,80);
draw.fillRect(495,50,100,80);
draw.fillRect(495,135,100,80);
draw.fillRect(495,220,100,80);
draw.fillRect(495,305,100,80);
draw.fillRect(495,390,100,80);
draw.fillRect(495,475,100,80);
draw.fillRect(155,50,335,505);
}
I think your issue is here:
loadScreen();
You are calling loadScreen without passing it an event.
You can fake it by doing this:
loadScreen({keyCode:73});
Note that when loadScreen is set to be called by an Event here:
document.addEventListener('keydown', loadScreen);
…every time a keyboard key is pressed down, an event object is passed as the first argument, and that event object contains a keyCode value that corresponds with the key pressed.
I was able to wrap your code in a test HTML document, and it produced some nice-looking gray rectangles:
<!DOCTYPE html>
<html>
<head>
<title>Test of Stackoverflow question 49583733</title>
<script type="text/javascript">
window.addEventListener('load', () => {
your code here, adding {keyCode:73}
}) ;
</script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

Cannot reach for properties or methods

I have difficulties understanding why my variable is undefined.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<title>webPage</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="JS/const.js"></script>
<script src="JS/event.js"></script>
<script src="JS/Player.js"></script>
<script src="JS/Map.js"></script>
<script src="JS/App.js"></script>
</body>
</html>
So i assume that the browser reads the Player file first, then the Map file and the the App file(correct me if i'm wrong).
App.js
var app;
var App = function (){
this.map = new Map();
this.player = new Player();
};
(function (){
app = new App();
})();
But when i want to reach for a property or a method of the Map class for exemple app.map.msg, firebug throws a typeError and says that app is not defined... Plus, typeError means that the variable does exist but that the operation you're trying to perform is not appropriate for the value it contains.
So it means my browser acknowledges my variable but not my App class??
I'm really confused so any help will be appreciated!!
Make sure you defined map correctly.
here is a working example tested on fiddle.
var app;
function Map() {
this.msg = " hey, i am map" ;
}
function Player () {
this.msg = " hey, i am player" ;
}
var App = function (){
this.map = new Map();
this.player = new Player();
};
(function (){
app = new App();
document.getElementById ( 'output' ) .innerHTML = app.map.msg
})();
http://jsfiddle.net/bdsduv08/

I want to know why this is not working, all im trying to do is get an image and use it as a stage child for my canvas

HTML CODE:
I HAD TO ADD SOMETHING TO DESCRIBE THE CODE, DONO Y
so obviously this is html code, don't know why its not running.
the code after this is javascript. If my code is very bad and doesn't make any sense, what im looking for is basically a way to use loadqueue to load an image and then set it as a background for a game.
<!DOCTYPE html>
<html>
<head>
<title>My Game</title>
<link href="assets/MyGame.css" rel="stylesheet" type="text/css"/>
<script src="https://code.createjs.com/preloadjs-0.6.1.min.js"></script>
<script src="https://code.createjs.com/tweenjs-0.6.1.min.js"></script>
<script language="javascript" type="text/javascript"
src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
<script language="javascript" type="text/javascript" src="MyGame.js"
></script>
</head>
<body>
<canvas id="demoCanvas" width="1000" height="700"></canvas>
</body>
</html>
var stage;
window.onload = function()
{
var queue = new createjs.LoadQueue(true);
queue.on("fileload", handleFileLoad, this);
queue.loadFile({id:"image", src:"assets/space.jpg"});
queue.load();
stage = new createjs.Stage("demoCanvas");
}
function handleFileLoad(event) {
// A reference to the item that was passed in to the LoadQueue
var item = event.item;
var type = item.type;
// Add any images to the page body.
if (type == createjs.LoadQueue.IMAGE) {
stage.addChild(event.result)
stage.update;
}
}
I believe that stage.update; should be stage.update(); as it is a method and not a property
I can spot two immediate issues:
you are trying to add the loaded image directly to the stage. It needs to be wrapped in a Bitmap first: stage.addChild( new createjs.Bitmap( event.result ));
you aren't calling stage.update() - you forgot the parenthesis.

Calling function from external JS

I am trying to call a function from an external .js file but the console is returning errors and the function is not being called. How do I correct my code and be able to call the function properly.
Here is the main .html file:
<html>
<head>
<script type="text/javascript" src="xp.js">
</script>
<script type="text/javascript">
window.onload = xyz.makeShape.Circle();
</script>
</head>
<body>
<canvas id="xyz" width="600" height="600"></canvas>
</body>
</html>
And here is the .js file:
var xyz = xyz || {};
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape = {
Circle : function() {
console.log('working');
}
}
EDIT
I am getting 2 errors in the console:
Error 1
TypeError: canvas is null
window.onload = xyz.makeShape.Circle;
Error 2
TypeError: xyz.makeShape is undefined
window.onload = xyz.makeShape.Circle;
Change this:
window.onload = xyz.makeShape.Circle();
to this:
window.onload = xyz.makeShape.Circle;
window.onload needs to be set to a function reference, not to the results of calling a function.
You also can't do these two lines from the <head> section before the DOM is loaded:
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
You need to execute those after the DOM has been loaded. There are multiple possible strategies for doing that. The easiest for what you already have would be to execute them in your onload handler since you know the DOM is already loaded there. You could also move the script tag that loads your external .js file to the end of the <body> section and the DOM will already be ready then when that js file runs.
You will just need to include the js file using the <script> tags - either in your header or footer.
<script type="text/javascript" src="js/yourjsfile.js"></script>
Now you can call functions from that script as if they were in the current file
Edit
If you're sure that the file is already included (first make sure you've got the path right) next you need to check your console from errors that may be arising from the included file. The code you've supplied looks right.
External js:
var xyz = xyz || {};
xyz.makeShape = {
Circle: function () {
console.log('working');
}
}
Internal js:
window.onload = function () {
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape.Circle();
}
Tested and works

Categories

Resources