moving canvas box with arrows - javascript

I've been trying to make a simple canvas box move with arrow keys. Here is the code: http://cssdeck.com/labs/stexplorer
And here also:
$(function() {
var n = 3;
var xD = 0;
var yD = 0;
//var move;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ss = {
"x": 0,
"y": 0,
"width": 100,
"height": 75
};
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(ss.x, ss.y, ss.width, ss.height);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.stroke();
}
function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
ss.x = x;
ss.y = y;
}
$(document).keydown(function(e) {
xD = e.which == 37 ? -1 : xD;
xD = e.which == 39 ? 1 : xD;
yD = e.which == 38 ? -1 : yD;
yD = e.which == 40 ? 1 : yD;
e.preventDefault();
});
$(document).keyup(function(e) {
xD = e.which == 37 ? 0 : xD;
xD = e.which == 39 ? 0 : xD;
yD = e.which == 38 ? 0 : yD;
yD = e.which == 40 ? 0 : yD;
e.preventDefault();
});
render();
setInterval(move, .01);
});
body {
margin: 0;
}
#canvas {
border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
This code should be doing the following:
Whenever I press an arrow key, the box should move
It would be great if I could make the canvas width = "100vw" and height = "100vh"

Your render method will only be fired initially, you should add it as the last line of the move method, so the canvas will render the new position after every move.
function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
ss.x = x;
ss.y = y;
render(); // add this line
}

Try this solution, click on result screen and than use keyboard arrow keys, also if this works for you mark my solution as answer, do post comment if you need anything else
var canvas;
var ctx;
var dx = 5;
var dy = 5;
var x = 150;
var y = 100;
var WIDTH = 300;
var HEIGHT = 200;
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function doKeyDown(evt){
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (y - dy > 0){
y -= dy;
}
break;
case 40: /* Down arrow was pressed */
if (y + dy < HEIGHT){
y += dy;
}
break;
case 37: /* Left arrow was pressed */
if (x - dx > 0){
x -= dx;
}
break;
case 39: /* Right arrow was pressed */
if (x + dx < WIDTH){
x += dx;
}
break;
}
}
function draw() {
clear();
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "purple";
circle(x, y, 10);
}
init();
window.addEventListener('keydown',doKeyDown,true);
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Test</title>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="300" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>

Related

how to define a color for an instance of a class in Java Scipt

I've making a breakout game and I had to make some blocks and give them random colors defined in a array, but for making more blocks I had to use a for loop. So, when I add them to my update function, colors are flashing at frame rate. I think you'll understand better if you run the snippet
one more thing: that canvasRendering...rundedRectangle is a function that draws rounded edge rectangles someone please find a solution!
CanvasRenderingContext2D.prototype.roundedRectangle = function(x, y, width, height, rounded) {
const radiansInCircle = 2 * Math.PI;
const halfRadians = (2 * Math.PI)/2;
const quarterRadians = (2 * Math.PI)/4 ;
// top left arc
this.arc(rounded + x, rounded + y, rounded, -quarterRadians, halfRadians, true);
// line from top left to bottom left
this.lineTo(x, y + height - rounded);
// bottom left arc
this.arc(rounded + x, height - rounded + y, rounded, halfRadians, quarterRadians, true) ;
// line from bottom left to bottom right
this.lineTo(x + width - rounded, y + height);
// bottom right arc
this.arc(x + width - rounded, y + height - rounded, rounded, quarterRadians, 0, true) ;
// line from bottom right to top right
this.lineTo(x + width, y + rounded) ;
// top right arc
this.arc(x + width - rounded, y + rounded, rounded, 0, -quarterRadians, true) ;
// line from top right to top left
this.lineTo(x + rounded, y) ;
};
var canvas= document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
function Player(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show = function(){
ctx.beginPath();
ctx.rect(this.x, this.y, this.w, this.h);
ctx.fillStyle = "#ffff";
ctx.fill();
ctx.closePath();
};
this.move = function(speed){
this.x += speed;
};
}
function Ball(x,y,r){
this.x = x;
this.y = y;
this.r = r;
this.show = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2* Math.PI);
ctx.fillStyle = "tomato";
ctx.fill();
ctx.closePath();
};
this.move= function(speedX,speedY){
this.show();
this.speed = 2;
this.x += speedX;
this.y += speedY;
};
}
var colors = ['#A5E75A','#7254AD','#FFD606','#FF093D'];
function Block(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.status =1;
this.show= function(color){
ctx.beginPath();
ctx.roundedRectangle(this.x,this.y,this.w,this.h,5);
//ctx.arc(this.x,this.y,10,0,2*Math.PI);
//ctx.fillStyle = colors[Math.floor(Math.random()*colors.length)];
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
};
}
var player = new Player(canvas.width/2-50,780,100,20);
var ball = new Ball(player.x+player.w/2, player.y,15);
var rigthPressed = false;
var leftPressed = false;
var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var rc = {blockRow : 0,
blockCol : 0};
for(let i = 0; i < blockCount; i++){
blocks.push(new Block(rc.blockCol*60+25,rc.blockRow*60-30,50,50));
rc.blockCol++;
if(i % noInRow === 0){
rc.blockRow++;
rc.blockCol = 0;
}
}
window.addEventListener("keydown", function(e){
if(e.keyCode == 39){
rigthPressed = true;
}
if(e.keyCode == 37){
leftPressed = true;
}
});
window.addEventListener("keyup", function(e){
if(e.keyCode == 39){
rigthPressed = false;
}
if(e.keyCode == 37){
leftPressed = false;
}
});
function objMovement(){
if(rigthPressed){
player.move(5);
if (player.x > canvas.width-player.w){
player.x = canvas.width-player.w;
}
}
if(leftPressed){
player.move(-5);
if(player.x < 0){
player.x = 0;
}
}
if(ball.x > canvas.width-ball.r || ball.x < 0+ball.r){
ballSpeedX = -ballSpeedX;
}
if (/*ball.y > canvas.height-ball.r ||*/ball.y < 0+ball.r){
ballSpeedY = -ballSpeedY;
}
if(ball.x<player.x+player.w &&ball.x>player.x && ball.y>player.y && ball.y<player.y+player.h){
ballSpeedY = -ballSpeedY;
ballSpeedX= ballSpeedX;
}
function Bump(){
if (ball.x>player.x && ball.x<player.x+player.w/2){
if (ball.y >= player.y){
ballSpeedX = -5;
}
}
if(ball.x>player.x+player.w/2 && ball.x<player.x+player.w){
if(ball.y >= player.y){
ballSpeedX = 5;
}
}
}
//Bump();
}
function reload(){
if (ball.y>canvas.height){
//alert('gameOver');
ball.x =player.x+player.w/2;
ball.y = player.y-ball.r;
ballSpeedX = 0;
ballSpeedY = 0;
}
}
var ballSpeedX = 0;
var ballSpeedY = -0;
function collision(){
for(let i=1;i<blockCount;i++){
if(ball.x>blocks[i].x &&
ball.x<blocks[i].x+blocks[i].w &&
ball.y>blocks[i].y &&
ball.y<blocks[i].y+blocks[i].h){
blocks[i].status = 0;
ballSpeedY = -ballSpeedY;
blocks.splice(i,1);
blockCount--;
//ballSpeedX = 0;
//ballSpeedY = 0;
console.log('hit');
}
}
}
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
objMovement();
for(let i=1;i<blockCount;i++){
if(blocks[i].status == 1){
blocks[i].show(colors[Math.floor(Math.random()*colors.length)]);
}
}
collision();
ball.show();
ball.move(ballSpeedX,ballSpeedY);
player.show();
reload();
window.requestAnimationFrame(update);
}
update();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🌝🌝</title>
<style>
#body{
background-color: rgb(31, 30, 30);
}
#gameCanvas{
border: 15px solid rgb(44, 44, 44);
border-radius: 20px;
background-color:rgb(19, 18, 18);
margin: 250px;
}
</style>
</head>
<body id="body">
<canvas id="gameCanvas" width=400 height=800></canvas>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Because you remove and redraw all rectangles from the canvas each update and assign a new color on show, they get assigned a new color each update. You might be able to avert this by adding a property color to the rectangle, which is initialised (once, so in the initial for loop) with a random color, and alter the show function to use this.color rather than accept a color as an argument. This way, you don't assign a new color to a rectangle each update, and it won't change color each update.

detecting collisions on the canvas

im trying to make a game where collisions happen between the protagonist and the antagonist. I cant get the collision to work though, i've tried using the x and y position then the x and y positions plus the width and the height of the protagonist and the antagonist
var canvas = document.getElementById('canvas');
var PX = 10;
var PY = 10;
var PW = 10;
var PH = 10;
var P = PX + PY;
var EX1 = 100;
var EY1 = 100;
var EW1 = 10;
var EH1 = 10;
var E1 = EX1 + EY1;
window.addEventListener("keydown", charMove);
window.addEventListener("keyup", charMove);
window.addEventListener("keypress", charMove);
window.onload = function() {
context = canvas.getContext("2d");
canvas.style.background = "black";
var framesPerSecond = 30;
setInterval(function() {
draw();
move();
}, 1000/framesPerSecond);
}
function draw() {
//EX context.fillRect(PosX, PosY, width, height);
//draws protagonist
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "blue"
context.fillRect(PX, PY, PW, PH);
context.stroke();
context.closePath();
//draws antagonist(s)
context.beginPath();
context.fillStlyle = "red";
context.fillRect(EX1, EY1, EW1, EH1);
context.stroke();
context.closePath();
}
function move() {
}
function charMove(){
var x = event.which || event.keyCode;
if(x == 37){
PX -= 1;
}
if(x == 38){
PY -= 1;
}
if(x == 39){
PX += 1;
}
if(x == 40){
PY += 1;
}
}
//detect collision
setInterval(function() {
if(PX > EX1 || PX + PW < EX1 + EW1 && PY + PH > EY1 + EH1 || PY + PH < EY1 + EH1){
window.alert("collision");
}
}, 1);
<html>
<head>
</head>
<body>
<canvas width="500px" height="500px" id="canvas" class="canvas">
</body>
</html>
Your formula for collision is wrong.
This problem is called Axis Aligned Bounding Box collision.
Two AABBs collide if their projections to each axis collide. In your 2-dimensinal case you have to consider the horizontal and vertical projections.
The projections are segments of 1-d space. Collision for those is very easy: if the start or the end of a segment is on the other they collide. Formally start2 <= start1 <= end2 or start2 <= end1 <= end2
In code:
intersects([p.x, p.x + p.width], [e.x, e.x + e.width]) && intersects([p.y, p.y + p.height], [e.y, e.y + e.height])
where
function intersects(seg1, seg2) {
return contains(seg1, seg2[0]) || contains(seg1, seg2[1])
}
function contains(segment, point) {
return segment[0] <= point && point <= segment[1]
}

How do you move a drawing in javascript up down right and left

I was wondering how to move the red ball right and left (I already did, but its not working) and also how to move it up and down.
<canvas id="canvas" width="480" height="320"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var ball;
var obstacle;
var x = canvas.width / 2;
var y = canvas.height / 2;
var dx = 2;
var dy = -2;
var redballRadius = 10;
var ballRadius = 20;
var rightpressed = false;
var leftpressed = false;
var ballX = (canvas.width - redballDiameter) / 2;
var redballDiameter = redballRadius * 2;
function startGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball = new drawBall(30, 30, 'red', 20, 10);
obstacle = new drawObstacle(40, 30, 'blue', 15, 10);
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightpressed && ballX < canvas.width-redballDiameter) {
ballX += 7;
}
else if(leftpressed && ballX > 0) {
ballX -= 7;
}
}
//keyboard controls
document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightpressed = true;
}
else if(e.keyCode == 37) {
leftpressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightpressed = false;
}
else if (e.keyCode == 37) {
leftpressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(30, 30, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
function drawObstacle() {
x += dx;
y += dy;
ctx.beginPath();
ctx.arc(x, y, 20, 10, 1 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
}
setInterval(startGame, 10);
I am basically wondering how to move it up down right and left with the keys. Thanks
I took a look at your code. In your life cycle, you are calling drawBall, now sure what you are trying to do with the new there. anyways, I updated the function to use the ballX your key handling logic updates.
function drawBall() {
ctx.beginPath();
ctx.arc(ballX, 30, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
here is the working code pen. http://codepen.io/poda/pen/aNPPEp
move a ball to up, down, right and left.
it would be better to use object than use global variable of x_pos and y_pos of ball
function drawBall() {
this.ball_x = 30;
this.ball_y = 30;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.ball_x, this.ball_y, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
},
this.move = function() {
if(rightpressed && this.ball_x < canvas.width-redballDiameter) {
this.ball_x += 5;
}
else if(leftpressed && this.ball_x > redballDiameter) {
this.ball_x -= 5;
}
else if(uppressed && this.ball_y > redballDiameter) {
this.ball_y -= 5;
}
else if(downpressed && this.ball_y < canvas.height - redballDiameter) {
this.ball_y += 5;
}
},
this.collision = function() {
//stuff
}
}
Here's a fiddle

My HTML game is not running, what's wrong?

I wrote this game from a tutorial i read online, it was working just fine, until i messed it up, my developer tools console says theres a reference error but i just cant see it, please help, the error i get through my we developer console is "Uncaught ReferenceError: Draw is not defined(anonymous function) # games.html:228 "
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee;
display: block;
margin: 0 auto;
}
#checking {
margin-left:650px;
}
#checking1 {
margin-left:650px;
}
#checking2 {
margin-left:650px;
}
#checking3 {
margin-left:650px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<br/>
<div id ="checking">Current Position</div>
<div id ="checking1">Nothings Moving Bro</div>
<br/>
<div id ="checking3">Color State</div>
<div id ="checking2">Nope, still nothing</div>
<script>
// JavaScript code goes here
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth)/2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler,false);
document.addEventListener("keyup",keyUpHandler,false);
function keyDownHandler(e){
if(e.keycode == 39){
RightKeyPressed = true;
}else if(e.keycode == 37){
LeftKeyPressed = true;
}
}
function keyUpHandler(e){
if(e.keycode == 39){
RightKeyPressed = false;
}else if(e.keycode == 37){
LeftKeyPressed = false;
}
function randomInt(min,max){
return Math.floor(Math.random() * (max - min))+ min; }
function paddle(){
ctx.beginPath;
ctx.rect(paddleX,canvas.height - paddleheight,paddlewidth,paddleheight);
ctx.fillStyle="#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(x,y,ballRadius,0,Math.PI*2,false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function Draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawball();
paddle();
if(y + dy > canvas.height - 20 || y + dy < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if ( x + dx > canvas.width - 20 || x + dx < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx; }
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y ;
checking2.innerHTML = color ;
}
}
if(RightKeyPressed && paddleX < canvas.width - 50 ){
paddleX += 7;
}else if(LeftKeyPressed && paddleX > 0){
paddleX -= 7;
}
setInterval(Draw,10);
</script>
</body>
</html>
Your code throws the error because it cannot find the function Draw():
setInterval(Draw, 10);
This is because your function is not in the same scope. Your code structure is like this:
function keyUpHandler(e) {
...
function Draw(){
//Codes here
}
...
}
...
setInterval(Draw, 10);
Since the Draw() function is inside the keyUpHandler(e), it cannot be seen from any outside function (that is functions that are on a higher level/scope).
Hope this clears your mind :)
Check out this fiddle , you closing bracket of function keyDownHandlercode is wrong
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth) / 2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = true;
} else if (e.keycode == 37) {
LeftKeyPressed = true;
}
}
function keyUpHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = false;
} else if (e.keycode == 37) {
LeftKeyPressed = false;
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function paddle() {
ctx.beginPath;
ctx.rect(paddleX, canvas.height - paddleheight, paddlewidth, paddleheight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function zan(){
alert('test');
}
function Draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawball();
paddle();
if (y + dy > canvas.height - 20 || y + dy < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if (x + dx > canvas.width - 20 || x + dx < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx;
}
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y;
checking2.innerHTML = color;
}
if (RightKeyPressed && paddleX < canvas.width - 50) {
paddleX += 7;
} else if (LeftKeyPressed && paddleX > 0) {
paddleX -= 7;
}
setInterval(Draw, 10);
You probably forgot to close your keyuphandler function (currently you have like 3 function inside it until you finally close it at line 193).
add a function closure at about line 88 to close your keyuphandler.
Than you have a extra function closure at line 193 remove that and it works
(by function closure i mean brackets {} )

object moves through keyboard arrow keys using html5 and javascript

how can i move the object with keyboard keys using html5 and javascript. Here i tried it with below code but it is not moving can any one help to move the object using keyboard arrow keys?
<!DOCTYPE html>
<html>
<head>
</head>
<body onLoad="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='green'>
<canvas id="mycanvas"></canvas>
<script>
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false);
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false);
ctx.fill();
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();
//moves//
var xpos=500;
var ypos=550;
var xspeed=1;
var yspeed=0;
var maxspeed=5;
//boundaries//
var minx=500;
var miny=200;
var maxx=990;
var maxy=400;
//controller
var upPressed=0;
var downPressed=1;
var leftPressed=0;
var rightPressed=0;
function slowDownX()
{
if(xspeed > 0) xspeed=xspeed-1; if(xspeed<0) xspeed=xspeed+1;
}
function slowDownY()
{
if(yspeed > 0)
yspeed = yspeed-1;
if(yspeed < 0)
yspeed = yspeed+1;
}
function gameLoop()
{
xpos=Math.min(Math.max(xpos+xspeed,minx),maxx); ypos=Math.min(Math.max(ypos+yspeed,miny),maxy);
xpos = document.getElementById('mycanvas').style.left;
ypos = document.getElementById('mycanvas').style.top;
if (upPressed == 1)
yspeed = Math.max(yspeed - 3,-3*maxSpeed);
if (downPressed == 1)
yspeed = Math.min(yspeed + 3,3*maxSpeed)
if (rightPressed == 1)
xspeed = Math.min(xspeed + 1,1*maxSpeed);
if (leftPressed == 1)
xspeed = Math.max(xspeed - 1,-1*maxSpeed);
if (upPressed == 0 && downPressed == 0)
slowDownY();
if (leftPressed == 0 && rightPressed == 0)
slowDownX();
return setTimeout("gameLoop()",10);
}
function keyDown(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 1;
if (code == 40)
downPressed = 1;
if (code == 37)
leftPressed = 1;
if (code == 39)
rightPressed = 1;
}
function keyUp(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 0;
if (code == 40)
downPressed = 0;
if (code == 37)
leftPressed = 0;
if (code == 39)
rightPressed = 0;
}
</script>
</body>
</html>
Here are the basics of drawing a shape on the html canvas and moving it with arrowkeys
Disclaimer: this code is not best game technique, it’s meant for clear instruction. ;)
First create a few variables that define a ball:
// the ball will be at coordinates 70,75
var ballX=70;
var ballY=75;
// the ball will have a radius of 15;
var ballRadius=15;
Next create a function that will draw that ball at the specified coordinates
function draw(){
// clear the canvas for the next frame
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw a ball that the use can move with left/right arrow keys
// the ball's center will be at BallX / BallY
// the ball will have a radius of BallRadius
ctx.beginPath();
ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
Now listen for user’s keystrokes.
// Listen for when the user presses a key down
window.addEventListener("keydown", keyDownHandler, true);
When the user presses a key down:
If the user presses the left or right arrows, move the ball by changing it’s “ballX” coordinate.
After changing the balls position, redraw the canvas
This code handles when a key is down (called by the addEventListener):
// Here we just handle command keys
function keyDownHandler(event){
// get which key the user pressed
var key=event.which;
// Let keypress handle displayable characters
if(key>46){ return; }
switch(key){
case 37: // left key
// move the ball 1 left by subtracting 1 from ballX
ballX -= 1;
break;
case 39: // right key
// move the ball 1 right by adding 1 to ballX
ballX += 1;
break;
default:
break;
}
// redraw the ball in its new position
draw();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/TsXmx/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.strokeStyle="blue";
ctx.fillStyle="red";
var ballX=70;
var ballY=75;
var ballRadius=15;
var leftWall=30;
var rightWall=120;
draw();
function draw(){
// clear the canvas for the next frame
ctx.clearRect(0,0,canvas.width,canvas.height);
// tell canvas to start a new path
// draw walls on left and right
ctx.beginPath();
ctx.moveTo(leftWall,0);
ctx.lineTo(leftWall,canvas.height);
ctx.moveTo(rightWall,0);
ctx.lineTo(rightWall,canvas.height);
ctx.lineWidth=2;
ctx.stroke();
// draw a ball that the use can move with left/right arrow keys
ctx.beginPath();
ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
// Here we just handle command keys
function keyDownHandler(event){
// get which key the user pressed
var key=event.which;
// Let keypress handle displayable characters
if(key>46){ return; }
switch(key){
case 37: // left key
// move the ball 1 left by subtracting 1 from ballX
ballX -= 1;
// calc the ball's left edge
var ballLeft=ballX-ballRadius;
// Keep the ball from moving through the left wall
if(ballLeft<=leftWall){ ballX=leftWall+ballRadius; }
break;
case 39: // right key
// move the ball 1 right by adding 1 to ballX
ballX += 1;
// calc the ball's right edge
var ballRight=ballX+ballRadius;
// Keep the ball from moving through the right wall
if(ballRight>=rightWall){ ballX=rightWall-ballRadius; }
break;
default:
break;
}
// redraw everything
draw();
}
// Listen for when the user presses a key down
window.addEventListener("keydown", keyDownHandler, true);
}); // end $(function(){});
</script>
</head>
<body>
<p>Click in the red box to get keyboard focus</p>
<p>Then Move ball with left and right arrow keys</p>
<canvas id="canvas" width=200 height=150></canvas>
</body>
</html>
two ball are move diff. side on key board .
first ball to move to keyboard to up, down , right, left key
second ball move to A(left side), W(up side) ,D(right side) and S(down side).
just copy and past in your screen.
<html>
<head>
<title> game</title>
</head>
<body>
<canvas id="canvas" width="307" height= "211" style= "border:1px solid #ff0000 ;" mxrgin = right >
</canvas>
<script>
var x = 10;
var x1= 280;
var y = 10;
var y1 = 10;
var dx = 2;
var dx1 = 3;
var dy = 1;
var dy1 =1;
var ctx;
var ctx1;
var WIDTH=300;
var HEIGHT=200;
var a="";
var b="";
var sp= 500;
var timer=[];
var down = [];
var up;
document.onkeydown=k_down;
document.onkeyup=k_up;
var left=false;
var right=false;
var up1=false;
var down1=false;
var flag=false;
var aa=false;
init();
function k_down(e)
{
down[e.keyCode]=true;
clearInterval(timer);
//sp=10;
if(down[37])
{
if(sp>2)
{
sp++;
}
dy=0;
dx=-3;
left=true;
flag=false;
//down=[];
}
else if(down[38])
{
if(sp>2)
{
sp++;
}
dx=0;
dy=-4;
up1=true;
flag=false;
//down=[];
}
else if(down[39])
{
if(sp>2)
{
sp++;
}
dy=0;
dx=3;
right=true;
flag=false;
//down=[];
}
else if(down[40])
{
if(sp>2)
{
sp++;
}
dx=0;
dy=4;
down1=true;
flag=false;
//down=[];
}
if(down[65])
{
dy1=0;
dx1=-3;
}
else if(down[87])
{
dx1=0;
dy1=-4;
}
else if(down[68])
{
dy1=0;
dx1=3;
}
else if(down[83])
{
dx1=0;
dy1=4;
}
//console.log("speed++>"+sp);
timer=setInterval(draw,sp);
down[e.keyCode]=false;
}
function k_up(e)
{
up=e.keyCode;
//alert(sp);
if(sp<10)
{
sp=10;
clearInterval(timer);
timer=setInterval(draw,10);
}
//console.log("upp->>"+down);
if(left==true && up1==true)
{
//console.log("1");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=-3;
dy=-4;
flag=true;
}
else if(left==true && down1==true)
{
//console.log("2");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=-3;
dy=4;
flag=true;
}
else if(right==true && up1==true)
{
//console.log("3");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=3;
dy=-4;
flag=true;
}
else if(right==true && down1==true)
{
//console.log("4");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=3;
dy=4;
flag=true;
}
if(left==true)
{
if(flag==false){
dy=0;
dx=-3;
}
}
else if(up1==true)
{
if(flag==false){
dx=0;
dy=-4;
}
}
else if(right==true)
{
if(flag==false){
dy=0;
dx=3;
}
}
else if(down1==true)
{
if(flag==false){
dx=0;
dy=4;
}
}
if (up==37)
{
left=false;
}
else if (up==38)
{
up1=false;
}
else if (up==39)
{
right=false;
}
else if (up==40)
{
down1=false;
}
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, 307, 211);
}
function init() {
//ctx = $("#canvas").getContext("2d");
ctx = document.getElementById('canvas').getContext("2d");
//WIDTH = $("#canvas").width()
//HEIGHT = $("#canvas").height()
//canvas.addEventListener("click", getPosition, false);
return setInterval(draw, 10);
}
/*
function getPosition(event)
{
// var canvas = document.getElementById("canvas");
// var x = event.x;
//var y = event.y;
// x -= canvas.offsetLeft;
// y -= canvas.offsetTop;
//alert("x: " + x + " y: " + y);
}
*/
function draw() {
clear();
circle(x, y, 10);
circle(x1, y1, 10);
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
console.log("x->"+x)
if (x==10){
dx = -dx;
x += dx;
y += dy;
}
if (y==10){
dy = -dy;
x += dx;
y += dy;
}
if (x1 + dx1 > WIDTH || x1 + dx1 < 0)
dx1 = -dx1;
if (y1 + dy1 > HEIGHT || y1 + dy1 < 0)
dy1 = -dy1;
x1 += dx1;
y1 += dy1;
console.log("x1->"+x1)
if (x1==10){
dx1 = -dx1;
x1 += dx1;
y1 += dy1;
}
if (y1==10){
dy1 = -dy1;
x1 += dx1;
y1 += dy1;
}
}
</script>
</body>
</html>

Categories

Resources