【发布时间】:2014-03-12 22:39:59
【问题描述】:
这是我的第一篇文章,我在尝试完成我的代码时遇到了一些麻烦,我已经完成了基础知识,但需要一些指导:有人愿意帮忙吗?
这就是我正在尝试做的事情,但在挣扎:我已经停滞不前了!
添加一个键盘事件侦听器,使用 WASD 键更改 speedX 和 speedY:
'W' 增加 SpeedY
'S' 降低 SpeedY
'A' 降低 SpeedX
'D' 增加 SpeedX
确保 SpeedX 和 Speed Y 永远不会太快
在绘图函数中,使用 speedX 和 speedY 变量更改 x 和 y 位置。
如果圆圈在画布之外,则将其移动到另一侧。例如,如果球在画布的右侧,则将其移动到另一侧。在移动它之前确保球完全离开边缘,否则它可能会弹出。
这是我到目前为止的代码:
var canvas;
var ctx;
var width = 320;
var height = 240;
var speedX = 0; //how fast the ball is moving in the horizontal direction
var speedY = 0; //how fast the ball is moving in the vertical direction
var radius = 10;
var x = width / 2 - radius; //starting horizontal position
var y = height / 2 - radius; //starting vertical position
var circleColor = "#FF0000";
var rectangleColorBg = "#FFFFFF";
var rectangleColorStroke = "#000000";
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function circle(x,y,r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.fillStyle = rectangleColorBg;
ctx.strokeStyle = rectangleColorStroke;
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function draw() {
//update based on speedX and speed y
//update if the ball position is not inside the canvase.
//draw the background - see function above
rect(0,0,width,height);
//
//draw the circle - see function above
circle(x, y, radius, circleColor);
}
init();
【问题讨论】:
-
您的代码中没有键盘事件监听器的痕迹。你已经尝试了什么?
-
对不起,这是我最基本的代码,我这样发布是因为我的键盘事件监听器似乎不起作用。
-
您能否将此代码放入 jsfiddle 中,以便我们更轻松地提供帮助?
标签: javascript event-handling keyboard addeventlistener interactive