I’m a little lost and new to this.
So the code is with the help of online resources. How can I basically combine all three of these elements to appear and move at the same time? I want it to look like the game pong.
I understand why the canvas needs to be cleared for animations but why are they still “on top” of each other? How can I get all 3 into view?
const canvas = document.getElementById("pong")
const ctx = canvas.getContext("2d");
//ball//
const ball = {
x: 100,
y: 100,
vx: 5,
vy: 2,
radius: 8,
color: "red",
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
},
};
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.draw();
ball.x += ball.vx;
ball.y += ball.vy;
if (
ball.y + ball.vy > canvas.height - ball.radius ||
ball.y + ball.vy < ball.radius
) {
ball.vy = -ball.vy;
}
if (
ball.x + ball.vx > canvas.width - ball.radius ||
ball.x + ball.vx < ball.radius
) {
ball.vx = -ball.vx;
}
raf = window.requestAnimationFrame(draw);
}
canvas.addEventListener("mouseover", (e) => {
raf = window.requestAnimationFrame(draw);
});
canvas.addEventListener("mouseout", (e) => {
window.cancelAnimationFrame(raf);
});
ball.draw();
// pong paddles //
ctx.strokeStyle = "purple";
var posY = 0;
var lineLength = 80;
var lineWidth = 10;
var speed = 2;
function drawLine() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(10, posY);
ctx.lineTo(10, posY + lineLength);
ctx.stroke();
}
function moveLine() {
posY += speed;
if (posY < 0 || posY > canvas.height) {
speed = speed * -1;
}
}
function loop() {
// clear old frame;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveLine();
drawLine();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
//Paddle 2//
ctx.strokeStyle = "purple";
var posY = 0;
var lineLength = 80;
var lineWidth = 10;
var speed = 2;
function drawLine() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(200, posY);
ctx.lineTo(200, posY + lineLength);
ctx.stroke();
}
function moveLine() {
posY += speed;
if (posY < 0 || posY > canvas.height) {
speed = speed * -1;
}
}
function loop() {
// clear old frame;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveLine();
drawLine();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
New contributor
Kristina B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.