undefined variable problem involving document.keydown () function - javascript

Here's the problem, document.onkeydown = checkkeycode
I'm passing two variable to checkeycode e which is storing the event and hence keycode and the array circle which I want to update with variable c's latest position. when I pass circle to the function, it becomes undefined hence
{circle[4] = c._.ty};
returns an undefined error
I tried putting document.write(circle);
into the document and it just wrote undefined and when I switched it with E it became a keyboard object. What I need solved is:
how do I pass the array circle to the function so that when raphael translates the circle, it updates the values in circle?
in the if (keycode == blah ) do I just do {c.translate(value)} {circle[4] = c._.ty} ?
do I append two different function to a single if event?
<html>
<head>
<script language="javascript" type="text/javascript" src="/home/andrew/Documents/rahpael/raphael-min.js"></script>
</head>
<body>
<script language="javascript">
var paper = Raphael(50, 50, 420, 300);
var d = paper.rect(150, 150, 30, 30);
var c = paper.circle(50, 50, 40);
var circle = [c.attrs.cy, c.attrs.cx, c.attrs.r, c._.tx, c._.ty];
var rectie = [ d.attrs.x, d.attrs.y, d.attrs.height, d.attrs.width];
document.onkeydown = checkKeycode
function checkKeycode(e, circle) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (keycode == 40) { c.translate(0, 10)}; //{circle[4] = c._.ty};// down
if (keycode == 39) { c.translate(10, 0)}; // right
if (keycode == 38) { c.translate(0, -10)}; // up
if (keycode == 37) { c.translate(-10, 0)}; // left
}
// deleted some comments I've made so far.
</script>
</body>
</html>

A couple of issues there:
1) Passing arguments
I'm passing two variable to checkeycode
No, you aren't. The browser will pass one argument to it, the event (unless it's IE, but you've handled that).
If you change:
document.onkeydown = checkKeycode
to
document.onkeydown = function(e) {
checkKeycode(e, circle);
};
...you'll be passing in the circle you defined at global scope.
2) Names
Your checkkeycode function accepts the arguments e and circle, but appears to use e and c instead.
(Your checkkeycode code already closes over the circle at global scope anyway, so you could just drop the circle argument from the definition of checkkeycode and use circle rather than c. But best to keep things modular if you can, by passing the argument into the function.)
So if you're going modular and just closing over circle in the event handler:
var paper = Raphael(50, 50, 420, 300);
var d = paper.rect(150, 150, 30, 30);
var c = paper.circle(50, 50, 40);
var circle = [c.attrs.cy, c.attrs.cx, c.attrs.r, c._.tx, c._.ty];
var rectie = [ d.attrs.x, d.attrs.y, d.attrs.height, d.attrs.width];
document.onkeydown = function(e) {
return checkKeycode(e, circle); // Event handler is closure over `circle`
};
// v-- `c`, not `circle`
function checkKeycode(e, c) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (keycode == 40) { c.translate(0, 10)}; //{circle[4] = c._.ty};// down
if (keycode == 39) { c.translate(10, 0)}; // right
if (keycode == 38) { c.translate(0, -10)}; // up
if (keycode == 37) { c.translate(-10, 0)}; // left
}

Related

bizzare putImageData action

Here is my code :
var ctx = document.getElementById("map").getContext("2d");
var ZeroX = 0;
var ZeroY = 0;
ctx.beginPath();
ctx.fillRect(100, 200, 100, 50); //Drawed a black rectangle
function moveMap(evt) {
var key = evt.keyCode || evt.which;
if (key == 38) { //UP
moveDirect(0, 20, false);
}
else if (key == 40) { //DOWN
moveDirect(0, 20, true);
}
else if (key == 39) { //RIGHT
moveDirect(20, 0, true);
}
else if (key == 37) { //LEFT
moveDirect(20, 0, false);
}
}
function moveDirect(X, Y, minus) {
if (minus == false) {
ZeroX -= X;
ZeroY -= Y;
}
else {
ZeroX += X;
ZeroY = Y;
}
var lol = ctx.getImageData(ZeroX, ZeroY, 3000, 3000);
ctx.clearRect(ZeroX, ZeroY, 3000, 3000);
ctx.putImageData(lol, 0, 0);
}
<body onkeypress="moveMap(event)">
<canvas id="map" width="500" height="500">Map </canvas>
</body>
If you run this snippet and click on one of the arrows on the keyboard, you'll see that the rectangle moves in the opposite
direction because I wanted to make like the screen was a camera in a
game. That's done on purpose
But if after you clicked on the arrow's oppsite (Up = Down, Left = Right,
etc), you will see that you must click two times to make it move in
the other direction. Try this with other arrows, still the same.
And if you press the same arrow many times, it's gap travelled becomes
bigger and bigger, but logically it must the same.
I want it to respond directly, not on two clicks and that the gap is always the same. Please explain in your answer why this is happennings. Thaks beforehand!

HTML5 Canvas - Keyboard keys do not respond

I'm trying to implement key input in my ping-pong game. The main point is that the up and down arrow keys don't work at all. My browser console doesn't display any errors messages.
Here is my code, this is WIP some Objects are not implemented yet
var playerBat = {
x: null,
y: null,
width: 20,
height: 80,
UP_DOWN: false,
DOWN_DOWN: false,
update: function() {
// Keyboard inputs
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
var key = {
UP: 38,
DOWN: 40
};
function onKeyDown(e) {
if (e.keyCode == 38)
this.UP_DOWN = true;
else if (e.keyCode == 40)
this.DOWN_DOWN = true;
}
function onKeyUp(e) {
if (e.keyCode == 38)
this.UP_DOWN = false;
else if (e.keyCode == 40)
this.DOWN_DOWN = false;
}
this.y = Math.max(Math.min(this.y, Canvas_H - this.height), 0); // Collide world bounds
},
render: function() {
ctx.fillStyle = '#000';
ctx.fillRect(this.x, this.y, this.width, this.height);
if (this.UP_DOWN)
this.playerBat.y -= 5;
else if (this.DOWN_DOWN)
this.playerBat.y += 5;
}
};
The events are firing, the problem is that you're adding them on each update. What you'll want to do it take the callbacks and the addEventListeners outside in a method such as addEvents, which should be called ONCE during initialization. Currently the huge amount of event handlers being triggered kills the page.
function addEvents() {
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
var key = {
UP: 38,
DOWN: 40
};
function onKeyDown(e) {
if (e.keyCode == key.UP) {
playerPaddle.UP_DOWN = true;
}
if (e.keyCode == key.DOWN) {
playerPaddle.DOWN_DOWN = true;
}
}
function onKeyUp(e) {
if (e.keyCode == key.UP) {
playerPaddle.UP_DOWN = false;
}
if (e.keyCode == 40) {
playerPaddle.DOWN_DOWN = key.DOWN;
}
}
}
After reviewing it further there are some other problems. First of all, the logic for actually changing the X and Y of the paddle should be within the update method (since that's what's usually used to change object properties), while the render method should simply draw the shapes and images using the object's updated properties.
Second, you're trying to access this.playerBat.y within the render method, however 'this' actually IS the playerBat. So in order to properly target the 'y' property you'd need to write this.y instead.
I also noticed that you've got a key map, with UP and DOWN keycodes defined, but don't actually use it, instead you use numbers. Maybe something you were planning on doing?
I reimplemented the code you have provided and added a init function to playerBat that attaches the event listeners for keydown and keyup events. I just kept the relevant bits and implemented objects as functions, but the concept should still be the applicable.
The callback function passed into addEventListener needs to bind this, otherwise the this value inside the callback (this.UP_DOWN and this.DOWN_DOWN) won't be the same as the this value in the enclosing scope; the one value you intended.
<canvas id='canvas' style="background:#839496">Your browser doesn't support The HTML5 Canvas</canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-20;
var ctx = canvas.getContext('2d');
var Canvas_W = Math.floor(canvas.width);
var Canvas_H = Math.floor(canvas.height);
/*
* Define a Player object.
*/
function PlayerBat(){
this.x = null;
this.y = null;
this.width = 20;
this.height = Canvas_H/3;
this.UP_DOWN = false;
this.DOWN_DOWN = false;
this.init = function() {
console.log('init');
// MUST bind `this`!
window.addEventListener('keydown', function(e){
console.log('keydown');
if (e.keyCode == 38) this.UP_DOWN = true;
else if (e.keyCode == 40) this.DOWN_DOWN = true;
}.bind(this), false);
// MUST bind `this`!
window.addEventListener('keyup', function(e){
console.log('keyUp')
if (e.keyCode == 38) this.UP_DOWN = false;
else if (e.keyCode == 40) this.DOWN_DOWN = false;
}.bind(this), false);
};
this.update = function() {
var key = {UP: 38, DOWN: 40};
this.y = Math.max(Math.min(this.y, Canvas_H - this.height), 0);
};
this.render = function() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw paddle
ctx.fillStyle = '#00F';
ctx.fillRect(this.x, this.y, this.width, this.height);
this.y = (this.UP_DOWN) ? this.y - 5 : ((this.DOWN_DOWN) ? this.y + 5 : this.y );
};
}
function GameRunner(){
// Create instance of player
var playerBat = new PlayerBat();
playerBat.init();
// Execute upon instantiation of GameRunner
(function () {
playerBat.x = playerBat.width;
playerBat.y = (Canvas_H - playerBat.height) / 2;
})();
function step() {
playerBat.update();
playerBat.render();
requestAnimationFrame(step);
}
// Public method. Start animation loop
this.start = function(){
requestAnimationFrame(step);
}
}
// Create GameRunner instance
var game = new GameRunner();
// Start game
game.start();
</script>

Slow performance with javascript/html canvas

So, I've created myself a little demo with javascript/html canvas in the context of a gameloop. You can move a small square by pressing the w,a,s,d keys. However, when held down for more than 3 or 4 seconds, the canvas becomes stuttery and the square almost stops moving.
Here's the javascript;
// --------------------------------------------------------------------
// -- MAIN GAME LOOP
// --------------------------------------------------------------------
function gameLoop(){
update();
render();
requestAnimationFrame(gameLoop);
}
function update(){
processInput();
};
function render(){
var canvas = document.getElementById('viewport');
var ctx = canvas.getContext('2d');
if(upDown){
rect.top -= rect.speed;
}else if(downDown){
rect.top += rect.speed;
}else if(leftDown){
rect.left -= rect.speed;
}else if(rightDown) {
rect.left += rect.speed;
}
ctx.clearRect(0, 0, 1024, 768);
ctx.beginPath();
ctx.rect(rect.left, rect.top, 50, 50, true);
ctx.closePath();
ctx.fill();
};
var rect = {
top: 0,
left: 0,
speed: 5
};
// --------------------------------------------------------------------
// -- OTHER FUNCTIONS
// --------------------------------------------------------------------
var rightDown = false;
var leftDown = false;
var upDown = false;
var downDown = false;
function processInput(){
$(document).keydown(function(e){
console.log(e.keyCode);
if(e.keyCode == 87){upDown = true;}
if(e.keyCode == 83){downDown = true;}
if(e.keyCode == 68){rightDown = true;}
if(e.keyCode == 65){leftDown = true;}
}).keyup(function(){
upDown = false;
downDown = false;
rightDown = false;
leftDown = false;
})
}
$(document).ready(function(){
requestAnimationFrame(gameLoop);
});
Anyone got any ideas?
Here's my codepen;
http://codepen.io/anon/pen/wKGJOr
The issue is because you're calling processInput (via update) within your gameloop. This function is attaching new keydown and keyup event handlers every time it is called. It's only necessary to call it once. Remove the call from update, and (for example) call it within the ready function instead:
$(document).ready(function(){
processInput();
requestAnimationFrame(gameLoop);
});
By registering more and more event handlers, you're causing a lot more code to run than is necessary, hence the stuttering.
Updated codepen.

Canvas diagonal movement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to put together a simple "game" in HTML5. However I can't get diagonal movement working.
The "diagonal movement" only works when the two buttons are pressed at exactly the same time. Even then it moves once. Here's the code:
// Getting canvas, and canvas context
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
//Keymap, later passed as method parameter
var map = [false,false,false,false];
// Top, Right, Bottom, Left
// Function for resetting keymap
var resetMap = function() {
for(i=0;i<map.length;i++) {
map[i] = false;
};
};
//Function for clearing the screen before drawing
var clrScrn = function() {
ctx.clearRect(0,0,500,500);
};
// The player character
var character = function() {
this.x = 50;
this.y = 50;
this.h = 50;
this.w = 50;
};
// Draw method of the character class
character.prototype.draw = function() {
ctx.fillRect(this.x,this.y,this.h,this.w);
};
// The move method of the character class
character.prototype.move = function(map) {
if(map[0] === true) {
if(map[1] == true) {
this.x+=5;
this.y-=5;
console.log("Pressed at the same time");
}
else {
this.y-=5;
}
}
else if(map[1] === true) {
this.x+=5;
}
else if(map[2] === true) {
this.y+=5;
}
else if(map[3] === true) {
this.x-=5;
}
};
//Making a new character
var player = new character();
player.draw();
// Drawing everything on screen
var render = function() {
clrScrn();
player.move(map);
player.draw();
resetMap();
requestAnimFrame(render);
};
//Calling the render function
render();
//Binding event listener to window,checking key down, likely the source of the problem
window.addEventListener("keydown",function(e){
if(e.keyCode == 38 && e.keyCode == 39) {
map[0] = true;
map[1] = true;
}
else if(e.keyCode == 38) {
map[0] = true;
}
if(e.keyCode == 39) {
map[1] = true;
}
if(e.keyCode == 40) {
map[2] = true;
}
if(e.keyCode == 37) {
map[3] = true;
}
console.log(e.keyCode);
},false);
//Binding event listener to key up
window.addEventListener("keyup",function(e){
resetMap();
},false);
In your render function:
player.move(map); // you move the player
player.draw(); // you draw the player
resetMap(); // you forget all pressed keys
The resetMap() is the reason you need to press the keys again in order to move just one more step.
Note that horizontal and vertical motions may accidentally work due to keyboard repeat when a key is pressed for a long time. But you shouldn't depend on key repeats for a game. You should detect key down and key up individually for individual keys in order to figure out if a key is pressed or not.
try looking at:
JavaScript multiple keys pressed at once
and then re-work your if/else logic a little bit.

html5 canvas. document.onkeypress arrow keys not working

I am trying to create a simple HTML5 Canvas football game. The game has three options, The player chooses left, right or centre to kick a ball, the goal keeper is random and will dive left, right or stay in the centre. I want the user to press the left, right or up arrow keys to trigger the player to kick the ball but I can't get my code to recognise when the arrow keys are pressed. I have tried different keys which will work ie, the return key.
function canvasApp(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Other Var's
document.onkeypress = function doKeyDown( e ) {
var key = e.keyCode;
if ( key == 37 ){
userChoice = key;
} else if (key == 38){
userChoice = key;
} else if (key == 39){
userChoice = key;
}
}
function draw() {
ctx.clearRect( 0, 0, canvas.width, canvas.height );
//------------------------------------------------
//Player shoots left
if ( userChoice == 37 ){
//More code
//------------------------------------------------
//Player shoots right
} else if ( userChoice == 39 ){
//More code
//------------------------------------------------
//Player shoots centre
} else if ( userChoice == 38 ) {
//More code
}
//------------------------------------------------
}
function gameLoop(){
window.setTimeout(gameLoop, framerate);
draw()
}
gameLoop();
}
document.onclick = function( e ){
window.clearTimeout();
}
If you need to see the full code let me know and I'll put a link up to a JSFiddle.
You're triggering the wrong event: use keydown even instead:
Check this page: http://help.dottoro.com/ljlkwans.php
The following is a snippet with jquery: if you use the keypress event it does not work.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(document).keydown(function(e){
var key = e.keyCode;
if ( key == 37 ){
console.log("left");
} else if (key == 38){
console.log("center");
} else if (key == 39){
console.log("right");
}
});
});
</script>
</html>

Categories