logo
TOOLS TO HELP YOU LEARN
teachers, students, everyone
Tools | Blog | Account | Learn
Login Status

Graphical Javascript for Beginners Part 3
Pong style game
Feb 22, 2017

To view part 2, click here. In this tutorial we'll continue to build upon our canvas and add a paddle and scoring for a pong game.

ADDING A Paddle:

Create a drawPaddle() function and add the following code to this method:

ctx.beginPath();
ctx.rect(200,canvas.height - 20,40,10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();

Add Varaibles for controlling Paddle on X-axis:

var paddleX = 100;
var paddleSpeed = 5;

Add the follow method to detect keystrokes

window.onload = function() {

/*
document.addEventListener('mousedown', function(event) {

console.log('mousedown');
}, false);*/

document.addEventListener('keydown', function(event) {

console.log('keydown' + event.keyCode);

}, false);

document.addEventListener('keyup', function(event) {

console.log('keyuppb ' + event.keyCode);

}, false);
}

 

The following assist in the detection of the mousedown and up:

canvas.addEventListener( 'mousedown', onMouseDown, false );
canvas.addEventListener( 'mouseup', onMouseUp, false );
canvas.addEventListener( 'mouseout', onMouseOut, false );
canvas.addEventListener( 'mousemove', onMouseMove, false );

function onMouseDown(event) {

var mouseX = event.offsetX;
var mouseY = event.offsetY;

}

function onMouseUp(event) {


}

function onMouseOut(event) {


}

function onMouseMove(event) {
//event.offsetX, event.offsetY

}

ALTERNATIVE keycode detection

this.document.onkeydown = keyPressed;

this.document.onkeyup = keyRelease;

function keyPressed(event) {
 
console.log("text" + event.keyCode);
}
function keyRelease(event) {
//code
}

 

 

document.addEventListener("keydown", keyDownHandler, false); 
document.addEventListener("keyup", keyUpHandler, false); function keyDownHandler(e) { if(e.keyCode == 39) { }}
function keyUpHandler(e) { if(e.keyCode == 39) { } }

 



Comments:




No comments posted

blog

Past Posts

Dropbox Public Folder Alternative
Jun 4, 2017

Getting Started with NodeJS
May 1, 2017

Scratch Intro: Racing Game
Jan 15, 2017

Five Best Educational Tools For Teachers
Feb 3, 2017

Coding Gravity
Feb 22, 2017

Drones in Eduction
March 2, 2017

Javascript Intro
April 1, 2017

iPhone Streaming Audio App
April 15, 2017

Installing MySQL
May 15, 2017

 

 


 

Thank You!