admin管理员组文章数量:1327114
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>
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>
Share
Improve this question
edited Jul 19, 2013 at 13:34
tckmn
59.4k27 gold badges118 silver badges156 bronze badges
asked Jul 19, 2013 at 13:32
koutilyakoutilya
211 silver badge3 bronze badges
3
-
1
Have you checked your browser's console for errors? Maybe your browser is throwing an exception like
WhitespaceError:Confused by lack of indenting
. (OK, that was snarky, but really it only takes a few seconds to run your code through jspretty. to make it readable for us - though for your own sake you should be including some appropriate indenting as you go, and I was serious about checking your browser's console for errors.) – nnnnnn Commented Jul 19, 2013 at 13:37 - but when i replace the canvas object with an image it is moving – koutilya Commented Jul 19, 2013 at 13:46
-
Your code draws something on the canvas when the page first loads, and then never updates it again. You have a bunch of calculations for speeds and so forth, but nowhere do you repaint or move the canvas. As far as replacing the canvas with an image, I don't see how an image could move either given that, again, your code doesn't ever try to move anything... Maybe the second and third lines inside
gameLoop()
have the assignment the wrong way around and you intended to set thestyle.top
and.left
rather than retrieving them? – nnnnnn Commented Jul 19, 2013 at 13:51
2 Answers
Reset to default 6Here 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 mand 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/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./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 mand 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>
本文标签: object moves through keyboard arrow keys using html5 and javascriptStack Overflow
版权声明:本文标题:object moves through keyboard arrow keys using html5 and javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742203262a2432349.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论