0

I'm trying to build brick-breaker game, however, the paddle does not show up. Seems like this.position.x, this.position.y, this.width, this.height is undefined..does anyone know why?? please help

let canvas=document.querySelector('.canvas')
let ctx=canvas.getContext('2d')

const gameWidth=800;
const gameHeight=500;

// ctx.clearRect(0, 0, 800, 500)


/////////////paddle class//////////
class Paddle{
    constructor(gameWidth, gameHeight){
        this.width=150;
        this.height=30;
        this.position={
            x:gameWidth/2-this.width/2,
            y:gameHeight-this.height-10
        };
    }

    draw(ctx){
        ctx.fillStyle='#32a852'
        ctx.fillRect(this.position.x, this.position.y, this.width, this.height)
    }
}
//////////controller///////
let paddle=new Paddle(gameWidth,gameHeight);
paddle.draw(ctx);///not working
ctx.fillRect(10,10,10,10)//this working
  • How are you including these in your HTML? Does app.js know what ctx is? In other words, is the code above paddle.js somewhere else than in app.js? If so then ctx will be undefined – bdbdbd Nov 02 '19 at 17:54
  • HTML simply just and link to app.js which is the one you see above. I put paddle.js and app.js together. ctx is define since ctx.fillReact works – Richard Piao Nov 02 '19 at 19:14
  • Did you check this? https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – ChatterOne Nov 02 '19 at 19:27

1 Answers1

0

The issue is that you're paddle position is not within the canvas size. Try adding this below the canvas variable definition canvas.width = window.innerWidth; canvas.height = window.innerHeight;

I tested it on my machine and it worked, so I hope this helps and if you need any clarification let me know!

Ameer
  • 1,980
  • 1
  • 12
  • 24
  • problem solved!!! but I totally don't understand why.. this is my css for canvas .canvas{ box-sizing: border-box; width: 800px; height: 500px; border: 2px solid black; } I also tried to add width and height directly to canvas HTML, it works without canvas.width = window.innerWidth; canvas.height = window.innerHeight; – Richard Piao Nov 03 '19 at 05:40
  • That only styles the style width, if you want a specific width and height use the DOM width and height ie `canvas.width` and `canvas.height` :) also it solves the problem because the x position and y position of your paddle is not within the canvas's size so it wouldn't be rendered within the canvas screen – Ameer Nov 03 '19 at 14:42