<html>
<header>
<link href='css.css' rel='stylesheet'>
<meta charset="UTF-8">
<title> moving box </title>
<script type= 'text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100,
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth){
mx = -4;
}
if (rectangle.x < 0){
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight){
my = -4;
}
if (rectangle.y < 0){
my = 4;
}
}
function keydowncontrol(){
if (e == 37){
mx = -1;
my = 0;
}
if (e == 38){
mx = 0;
my = -1;
}
if (e == 39){
mx = 1;
my = 0;
}
if (e == 40){
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
function init() {
checkmx();
checkmy();
window.onkeydown = keydowncontrol();// how can does this notice the key pressed
draw();
}
</script>
</header>
<body onload='setInterval(init,10)'>
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>
I am trying to animate a box. I'm not sure how the window.onkeydown and event.keycode work. My goal is to have the mx and my variables change depending on the keys pressed. Should keydowncontrol() be in the draw() function or init() function?
Try this:
<html>
<head>
<link href='css.css' rel='stylesheet' />
<meta charset="UTF-8" />
<title>Moving box</title>
<script type='text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth) {
mx = -4;
}
if (rectangle.x < 0) {
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight) {
my = -4;
}
if (rectangle.y < 0) {
my = 4;
}
}
function keydowncontrol(e) {
//alert(e);
if (e.keyCode == 37) {
mx = -1;
my = 0;
}
if (e.keyCode == 38) {
mx = 0;
my = -1;
}
if (e.keyCode == 39) {
mx = 1;
my = 0;
}
if (e.keyCode == 40) {
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
//keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
//document.attachEvent("onkeypress", keydowncontrol);
</script>
</head>
<body onload='setInterval(draw, 10)' onkeydown="keydowncontrol(event)">
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>
Related
Im making a pong game and I want to make the ball have a speedX and a speedY that is added to the ball that makes it move along the X and Y axis but im not sure how to adjust those variables based off of the balls angle. In function ballPhysics() I need to replace the 0's with something to get the speed it should go along that axis. But if anyone finds anything else that should be worked on itd be great if you let me know thanks.
let cvs, ctx;
let width = 600, height = 500;
let keysPressed = [];
class Wall {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
}
}
class Ball {
constructor(x, y , w, h, speedX, speedY, angle) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speedX = speedX;
this.speedY = speedY;
this.angle = angle;
}
}
let left = new Wall(25, 250, 10, 100, 10);
let right = new Wall(width-25, 250, 10, 100, 10)
let ball = new Ball(width/2, height/2, 5, 5, 0, 0, 0);
function ballPhysics() {
ball.x += ball.speedX;
ball.y += ball.speedY;
ball.speedX = 0//figure out direction;
ball.speedY = 0//figure out direction;
}
function start() {
ball.x = width/2;
ball.y = height/2;
if(Math.random() < 0.5) {
ball.angle = 90;
} else {
ball.angle = -90;
}
console.log(ball.angle);
}
function update() {
setInterval(function () {
ballPhysics();
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == 'KeyW' && left.y >= 0) {
left.y -= left.speed;
}
if(keysPressed[i] == 'KeyS' && left.y + left.h <= height) {
left.y += left.speed;
}
if(keysPressed[i] == 'ArrowUp' && right.y >= 0) {
right.y -= right.speed;
}
if(keysPressed[i] == 'ArrowDown' && right.y + right.h <= height) {
right.y += right.speed;
}
if(keysPressed[i] == 'Space') {
start();
}
}
}, 16)
}
function renderPlayers() {
ctx.fillStyle = '#FF0000';
ctx.fillRect(left.x, left.y, left.w, left.h);
ctx.fillRect(right.x, right.y, right.w, right.h);
}
function renderBall() {
ctx.fillStyle = '#0000FF';
ctx.fillRect(ball.x, ball.y, ball.w, ball.h);
}
function render() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
renderBall();
renderPlayers();
requestAnimationFrame(render);
}
window.addEventListener("DOMContentLoaded", function () {
cvs = document.getElementById("cvs");
ctx = cvs.getContext("2d");
cvs.width = width;
cvs.height = height;
update();
render();
});
window.addEventListener('keydown', function(e) {
if(!keysPressed.includes(e.code)) {
keysPressed.push(e.code);
}
});
window.addEventListener('keyup', function(e) {
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == e.code) {
keysPressed.splice(i, 1);
}
}
});
#cvs {
border: solid 1px black;
background: #D1C3C3;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Platformer</title>
<link rel="stylesheet" href="/style.css" />
<script src="/script.js" defer></script>
</head>
<body>
<canvas width="0" height="0" id="cvs"></canvas>
</body>
</html>
var canvas = document.getElementById('PongPad1');
// var canvasSize = document.getElementById("PongPad1").style.height;
var PongPad1 = canvas.getContext('2d');
PongPad1.speed = 3;
PongPad1.w = 50;
PongPad1.h = 100;
PongPad1.x = "";
PongPad1.y = "";
if(PongPad1.x == ""){
PongPad1.x = 20;
}
if(PongPad1.y == ""){
PongPad1.y = 20;
}
function draw() {
PongPad1.fillStyle = 'black';
PongPad1.fillRect( PongPad1.x , PongPad1.y , PongPad1.w, PongPad1.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 38) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h)
if(PongPad1.y > 0){
PongPad1.y = PongPad1.y - PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 40) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h);
//Canvas hieght - PongPad1.h
if(PongPad1.y < 175){
PongPad1.y = PongPad1.y + PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
var canvas1 = document.getElementById('PongPad2');
// canvas.setAttribute('style', 'border: 1px solid; position: fixed; top: 8px; left: 8px; z-index: 0; width: 500px; height: 500px;');
var PongPad2 = canvas1.getContext('2d');
PongPad2.speed = 3;
PongPad2.w = 50;
PongPad2.h = 100;
PongPad2.x = "";
PongPad2.y = "";
if(PongPad2.x == ""){
PongPad2.x = window.innerWidth - (40 + PongPad2.w);
}
if(PongPad2.y == ""){
PongPad2.y = 20;
}
function draw2() {
PongPad2.fillStyle = 'black';
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 87) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h)
if(PongPad2.y > 0){
PongPad2.y = PongPad2.y - PongPad2.speed;
}
draw2();
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 83) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h);
//Canvas hieght - PongPad1.h
if(PongPad2.y < 175){
PongPad2.y = PongPad2.y + PongPad2.speed;
}
draw2();
}
});
var canvas2 = document.getElementById('ball');
var ball = canvas2.getContext('2d');
ball.speed = 1;
ball.w = 10;
ball.h = 10;
ball.dx = "";
ball.dy = "";
if(ball.dx == ""){
ball.dx = 1 * (Math.round(Math.random()) * 2 - 1);
}
if(ball.dy == ""){
ball.dy = 1 * (Math.round(Math.random()) * 2 - 1);
}
ball.x = "";
ball.y = "";
if(ball.x == ""){
ball.x = 960;
}
if(ball.y == ""){
ball.y = -300;
}
function draw3() {
ball.fillStyle = 'black';
ball.fillRect( ball.x , ball.y , ball.w, ball.h);
}
setInterval(() => {
ball.clearRect( ball.x , ball.y , ball.w, ball.h);
ball.x = ball.x + (ball.speed * ball.dx);
ball.y = ball.y + (ball.speed * ball.dy);
draw3();
if(ball.y < 0){
ball.dy = 1;
}
//Math.round(window.innerHeight/2)
if(ball.y > 200){
ball.dy = -1;
}
draw3();
if(ball.x > window.innerWidth){
ball.dx = -1;
ball.speed = 1;
}
if(ball.x < 0){
ball.dx = 1;
ball.speed = 1;
}
if(PongPad1.x < ball.x + ball.w &&
PongPad1.x + PongPad1.w > ball.x &&
PongPad1.y < ball.y + ball.h &&
PongPad1.y + PongPad1.h > ball.y)
{
ball.dx = 1;
//ball.speed++;
}
if(PongPad2.x < ball.x + ball.w &&
PongPad2.x + PongPad2.w > ball.x &&
PongPad2.y < ball.y + ball.h &&
PongPad2.y + PongPad2.h > ball.y)
{
ball.dx = -1;
//ball.speed++;
}
//console.log(ball.y);
}, 10);
var test = window.innerWidth ;
var test2 = window.innerHeight ;
document.getElementById("test").textContent = "" + test + "," + test2 + "";
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="Pangea 8 logo 3.png" type="image/x-icon">
<meta name="keywords" content="Pangea 8"/>
</head>
<style>
.work{
position: static;
border: 3px solid #73AD21;
}
</style>
<body id="body">
<p id ="test">
hello
</p>
<div >
<canvas class = "work" id="ball" height = "469px" width = "1900px" ></canvas>
<canvas class = "work" id="PongPad1" height = "275px" > </canvas>
<canvas class = "work" id="PongPad2" height = "275px" width = "1900px" ></canvas>
</div>
</body></html>
^ Is my Pong game. Use W,S and Up, Down to make the paddles appear. I made the canvases have a green border so you can see them better. I want these canvases to be on the same plane, instead of the 3. They are not in synch, I need them to be. How can I make them overlap so they are on the same level?
position:absolute;
top:0;
left:0;
this created my desired outcome.
I'm new in programming things, So I wanted to start good projects with a snake game with canvas, Now I make one but it does not work well. I have a snake but I have a problem while adding it to the head.
ctx.fillStyle = "white";
drwhd.fillStyle ="blue";
for (var i = 0; i < snakeTrail.length; i++) {
ctx.fillRect(
snakeTrail[i].x * tileSize,
snakeTrail[i].y * tileSize,
tileSize,
tileSize
);
}
drwhd.fillRect(
snakeHead[k].x * tileSize,
snakeHead[k].y * tileSize,
tileSize,
tileSize
);
I tried these codes for the head . There is not an error but it should draw body with white and head with a blue. It draws all blue. I hope someone can fix this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Snake</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<div id="score"></div>
<div id="highscore"></div>
<script>
var score = 0;
var highScore = 1;
var gridSize = (tileSize = 20); // 20 x 20 = 400
var nextX = (nextY = 0);
//var jj = "https://i.hizliresim.com/p24p2r.png";
// TISSS YILAAAN
var defaultTailSize = 3;
var tailSize = defaultTailSize;
var snakeTrail = [];
var snakeHead = [];
var snakeX = (snakeY = 10);
// Amasya Elması
var appleX = (appleY = 15);
// Ekrana Çiz
function draw() {
// Yılanı sonraki pos'a (pozisyona) ilerlet - move snake to next pos
snakeX += nextX;
snakeY += nextY;
// Yılan Oyun Alanının Dışına Çıkarsa - Snake go to out of canvas
if (snakeX < 0) {
snakeX = gridSize - 1;
}
if (snakeX > gridSize - 1) {
snakeX = 0;
}
if (snakeY < 0) {
snakeY = gridSize - 1;
}
if (snakeY > gridSize - 1) {
snakeY = 0;
}
//Yılan Elmayı Yakalarsa - Snake Eats The Apple
if (snakeX == appleX && snakeY == appleY) {
tailSize++;
score++;
appleX = Math.floor(Math.random() * gridSize);
appleY = Math.floor(Math.random() * gridSize);
}
//Background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Snake
ctx.fillStyle = "white";
drwhd.fillStyle = "blue";
for (var i = 0; i < snakeTrail.length; i++) {
ctx.fillRect(
snakeTrail[i].x * tileSize,
snakeTrail[i].y * tileSize,
tileSize,
tileSize
);
drwhd.fillRect(
snakeHead[0].x * tileSize,
snakeHead[0].y * tileSize,
tileSize,
tileSize
);
//Yılan Kendine Çarparsa - Snake Hit Himself
if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) {
tailSize = defaultTailSize;
score = 0;
}
if (highScore < score) {
highScore = score;
}
}
// Amasya Elmasını Boya :D - Paint Apple
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);
//set snake trail
snakeTrail.push({
x: snakeX,
y: snakeY
});
snakeHead.push({
x: snakeX,
y: snakeY
});
while (snakeTrail.length > tailSize) {
snakeTrail.shift();
snakeHead.shift();
}
//PUANI YAZDIR
ctx.fillStyle = "white";
ctx.fillText("Skor : " + score, 25, 25);
ctx.fillText("En Yüksek :" + highScore, 25, 45);
}
// tuşlar
function keyDownEvent(e) {
if (e.keyCode == 87 && nextY != 1) {
nextX = 0;
nextY = -1;
}
if (e.keyCode == 83 && nextY != -1) {
nextX = 0;
nextY = 1;
}
if (e.keyCode == 68 && nextX != -1) {
nextX = 1;
nextY = 0;
}
if (e.keyCode == 65 && nextX != 1) {
nextX = -1;
nextY = 0;
}
}
var canvas, ctx;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
drwhd = canvas.getContext("2d");
document.addEventListener("keydown", keyDownEvent);
// her saniye X'i renderla
var x = 8;
setInterval(draw, 1000 / x);
</script>
</body>
</html>
I'm new to programming and I tried to make a game. You move a red block and when you hit a green block the you go back to (0,0) and the green block goes to a random location.
Now my question is how do I put a score counter in the game when I hit the green block that it counts +1.
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
document.onkeydown = anim;
window.onload=startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<button onmousedown="anim(e)" onmouseup="clearmove()" ontouchstart="moveup()">Start</button>
<br><br>
<p>press start to start
<br> use the buttons ↑ ↓ → ← on your keyboard to move stop with the space</p>
Changes
Added an <output> tag to display score.
Redefined event handlers/listeners
Details on changes are commented in demo
Demo
// Reference output#score
var score = document.getElementById('score');
// Declare points
var points = 0;
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
// Convert points to a real number
points = parseInt(points, 10);
// Increment points
points++;
// Set output#score value to points
score.value = points;
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
/* Set on click handler
|| When event occurs call startGame() / exclude
|| parenthesis
*/
document.onclick = startGame;
/* Register keydown event
|| When event occurs call anim() / exclude parenthesis
*/
document.addEventListener('keydown', anim, false);
/* When a callback is a named function / exclude the
|| parenthesis
*/
window.onload = startGame;
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
button {
font: inherit;
}
<br><br>
<button id='start'>Start</button>
<br><br>
<label for='score'>Score: </label>
<output id='score'>0</output>
<br><br>
<p>Click <kbd>Start</kbd> button</p>
<p>Use the buttons ↑ ↓ → ← on your keyboard to move stop with the spacebar.</p>
add
var chrashed = 0;
and use
if (myGamePiece.crashWith(myObstacle)) {
crashed++;
showCrashed;
return startGame();
}
https://jsfiddle.net/mplungjan/m4w3ahj1/
I can't find what is causing the canvas to show nothing. Please help me!
Here is the image that shows what is happening http://imgur.com/So67XMM
In the body tag I'm calling the function inicializar, like this: <
body onload="inicializar()">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 480;
var w = canvas.width;
var h = canvas.height;
var friction = 0.98,
alturaJogador,
larguraJogador,
pontosJogador,
espaco,
keys = [];
var jogador1 = {
x: w / 2,
y: h / 2,
s: 2,
vx: 0,
vy: 0,
dir: 0
};
var bola = {
x: canvas.width / 2,
y: 250,
d: 10,
s: 2,
vx: 0,
vy: 0
};
function inicializar() {
alturaJogador = 25;
larguraJogador = 25;
pontosJogador = 0;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
espaco = false;
setInterval(update, 10);
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2) {
return false;
}
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2) {
return false;
}
}
return true;
}
function update() {
if (keys[38]) {
if (jogador1.vy > -jogador1.s) {
jogador1.vy--;
}
}
if (keys[40]) {
if (jogador1.vy < jogador1.s) {
jogador1.vy++;
}
}
if (keys[39]) {
if (jogador1.vx < jogador1.s) {
jogador1.vx++;
}
}
if (keys[37]) {
if (jogador1.vx > -jogador1.s) {
jogador1.vx--;
}
}
if (keys[32]) {
espaco = true;
} else {
espaco = false;
}
var vB = 10;
var angle = Math.atan(Math.abs(jogador1.vy / jogador1.vx));
var vBx = Math.cos(angle) * vB;
if (jogador1.vx < 0) {
vBx *= -1;
}
var vBy = Math.sin(angle) * vB;
if (jogador1.vy < 0) {
vBy *= -1;
}
jogador1.vy *= friction;
jogador1.y += jogador1.vy / 2;
jogador1.vx *= friction;
jogador1.x += jogador1.vx / 2;
if (jogador1.x >= 575) {
jogador1.x = 575;
} else if (jogador1.x <= 0) {
jogador1.x = 0;
}
if (jogador1.y > 455) {
jogador1.y = 455;
} else if (y <= 0) {
jogador1.y = 0;
}
ctx.clearRect(0, 0, 600, 480);
ctx.beginPath();
ctx.fillRect(jogador1.x, jogador1.y, alturaJogador, larguraJogador);
ctx.fill();
ctx.beginPath();
ctx.arc(bola.x, bola.y, bola.d, 0, Math.PI * 2, true);
ctx.fill();
ctx.font = "32pt Tahoma";
ctx.fillText(pontosJogador, canvas.width - 70, 50);
ctx.fillText(jogador1.vx, canvas.width - 570, 50);
ctx.fillText(jogador1.vy, canvas.width - 570, 90);
ctx.fillText(jogador1.dir, canvas.width - 570, 130);
}
update();
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
canvas {
border: 1px solid #000000;
}
<canvas id="canvas" width="600" height="480">
Navegador não suporta HTML5
</canvas>
<!DOCTYPE html>
<head>
<title>Game</title>
<style type="text/css">
canvas {
border: 1px solid #000000;
}
</style>
</head>
<body onload="inicializar()">
<canvas id="canvas" width="600" height="480">
HTML5 not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 480;
var w = canvas.width;
var h = canvas.height;
var friction = 0.98,
alturaJogador,
larguraJogador,
pontosJogador,
espaco,
keys = [];
var jogador1 = {
x: w / 2,
y: h / 2,
s: 2,
vx: 0,
vy: 0,
dir: 0
};
var bola = {
x: canvas.width / 2,
y: 250,
d: 10,
s: 2,
vx: 0,
vy: 0
};
function inicializar() {
alturaJogador = 25;
larguraJogador = 25;
pontosJogador = 0;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
espaco = false;
setInterval(update, 10);
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2){
return false;
}
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2){
return false;
}
}
return true;
}
function update() {
if(keys[38]) {
if(jogador1.vy > -jogador1.s) {
jogador1.vy--;
}
}
if(keys[40]) {
if(jogador1.vy < jogador1.s) {
jogador1.vy++;
}
}
if(keys[39]) {
if(jogador1.vx < jogador1.s) {
jogador1.vx++;
}
}
if(keys[37]) {
if(jogador1.vx > -jogador1.s) {
jogador1.vx--;
}
}
if(keys[32]) {
espaco = true;
} else {
espaco = false;
}
var vB=10;
var angle=Math.atan(Math.abs(jogador1.vy/jogador1.vx));
var vBx = Math.cos(angle)*vB;
if (jogador1.vx < 0) {
vBx *= -1;
}
var vBy = Math.sin(angle)*vB;
if (jogador1.vy < 0) {
vBy *= -1;
}
jogador1.vy *= friction;
jogador1.y += jogador1.vy /2;
jogador1.vx *= friction;
jogador1.x += jogador1.vx/2;
if(jogador1.x >= 575) {
jogador1.x = 575;
} else if(jogador1.x <= 0) {
jogador1.x = 0;
}
if(jogador1.y > 455) {
jogador1.y = 455;
} else if(y <= 0) {
jogador1.y = 0;
}
ctx.clearRect(0, 0, 600, 480);
ctx.beginPath();
ctx.fillRect(jogador1.x, jogador1.y, alturaJogador, larguraJogador);
ctx.fill();
ctx.beginPath();
ctx.arc(bola.x, bola.y, bola.d, 0, Math.PI * 2, true);
ctx.fill();
ctx.font = "32pt Tahoma";
ctx.fillText(pontosJogador, canvas.width - 70, 50);
ctx.fillText(jogador1.vx, canvas.width - 570, 50);
ctx.fillText(jogador1.vy, canvas.width - 570, 90);
ctx.fillText(jogador1.dir, canvas.width - 570, 130);
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
</script>
</body>
</html>
Give the body an id:
<body id="body">
Then go into javascript to interact:
var body = document.getElementById("body");
body.onload = function () {
inicializar();
}
I hope this helped :)