<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Keyboard!</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Define the canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
//Draw the circle
function circle(x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
//Draw the rectangle
function rectangle(x, y, width, height) {
ctx.beginPath();
ctx.fillRect(x, y, width, height);
};
//Create the pong platform
function Platform() {
this.x = 150;
this.y = 375;
this.xSpeed = 5;
this.speed = 5;
};
//Move the pong platform
Platform.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0) {
this.xSpeed = 0;
} else if (this.x > width) {
this.xSpeed = width;
}
};
//Draw the pong platform
Platform.prototype.draw = function () {
rectangle(150, 375, 100, 25);
};
//Set the direction of the platform
Platform.prototype.setDirection = function (direction) {
if (direction === "stop") {
this.xSpeed = 0;
} else if (direction === "left") {
this.xSpeed = -5;
} else if (direction === "right") {
this.xSpeed = 5;
}
};
//Create the ball
function Ball() {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = Math.floor(Math.random() * 10);
this.ySpeed = Math.floor(Math.random() * 10);
this.size = 10;
this.speed = 5;
};
//Move the ball
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0) {
this.xSpeed = this.speed;
} else if (this.x > width) {
this.xSpeed = -this.speed;
}
if (this.y < 0) {
this.ySpeed = this.speed;
} else if (this.y > height) {
this.ySpeed = -this.speed;
}
if (this.size < 1) {
this.size = 1;
}
if (this.size > 20) {
this.size = 20;
}
this.Speed = Math.floor(Math.random() * 10);
};
//Draw the ball
Ball.prototype.draw = function () {
circle(this.x, this.y, this.size, true);
};
//reacting to the keyboard
var ball = new Ball();
var platform = new Platform();
var keyActions = {
32: "stop",
37: "left",
38: "up",
39: "right",
40: "down",
49: "1",
50: "2",
51: "3",
52: "4",
53: "5",
54: "6",
55: "7",
56: "8",
57: "9",
90: "zee",
88: "ex",
67: "see",
86: "vee"
};
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
platform.setDirection(direction)
});
//animating the ball
setInterval(function () {
ctx.clearRect(0, 0, width, height);
ball.draw();
ball.move();
platform.draw();
platform.move();
ctx.strokeRect(0, 0, width, height);
}, 30);
</script>
</body>
</html>
برچسب:
نویسنده: آیلین رضوانی