Reputation: 1
I am having trouble with my code. From what I am seeing, it should work, and it has worked for others, but it is not working for me. I am having trouble identifying the problem, if anyone can help.
I've tried googling similar issues, to no avail. Watching this from a YouTube video, but he has no problem with it. This is my code.
//This is importing the paddle from paddle.js
import Paddle from "/src/paddle";
//This is JavaScript. It sets the canvas
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");
//These variables will never change, and can be called upon
const GAME_HEIGHT = 800;
const GAME_WIDTH = 600;
/*This clears the screen, preventing the squares
from being redrawn over each other */
ctx.clearRect(0, 0, 800, 600);
//This is using the imported paddle and drawing it
let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);
//On a seperate note, I am having trouble actually getting the paddle to draw
paddle.draw(ctx);
//This is the separate file I am importing from
export default class Paddle {
//Sets what the paddle dimensions will be
constructor(gameWidth, gameHeight) {
//sets the width of the paddle
this.width = 150;
//sets the height of the paddle
this.height = 30;
//sets the area where the paddle spawns
this.position = {
x: gameWidth / 2 - this.width / 2,
y: gameHeight - this.height - 10
};
}
//This actually ends up drawing the paddle on the board
draw(ctx) {
ctx.fillStyle = "#0f0";
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
}
I expect it to display the paddle along the bottom middle of the game screen in a green color, but nothing is displayed there and I have no error messages.
Upvotes: 0
Views: 58
Reputation: 463
After replicating your code, I noticed the canvas size was by default only 300px by 150px. The paddle you are attempting to draw is outside the visible canvas area. Use:
ctx.canvas.width = GAME_WIDTH;
ctx.canvas.height = GAME_HEIGHT
To set the desired size of the canvas before you begin drawing to it.
Also note, when clearing the canvas, you are using hardcoded values
ctx.clearRect(0, 0, 800, 600)
- be sure to use the GAME_WIDTH and GAME_HEIGHT variables so if your resolution changes the area cleared is consistent.
Aside note, your GAME_WIDTH
is 600 and GAME_HEIGHT
is 800 - typical resolutions would have width as 800 and height as 600.
Upvotes: 1