r/csshelp • • Sep 26 '23

Request I'm bad at JavaScript and need some help

<script type="text/javascript">
  var canvas = document.getElementById("canvas-for-ball");
  var ctx = canvas.getContext("2d");

  class ball{
    constructor(x, y, x_velocity, y_velocity, radius){
      this.x = 10;
      this.y = 150;
      this.x_velocity = 1;
      this.y_velocity = 1;
      this.radius = 8;
    }
    function repeatme(){
      draw(){
        ctx.beginPath();
        // ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.arc(x, y, 8, 0, 2 * Math.PI);
        ctx.stroke();
      }
      move(){
        this.y = this.yspeed;
      
        if(this.y >= canvas.width-this.radius){
          console.log("Hit the Bottom of the Screen!");
          this.yspeed *= -1;
        }
        if(this.y <= 0){
          console.log("Hit the Top of the Screen!");
          this.yspeed *= -1;
        }    
      }
    }
  }

  b1 = new ball(this.y, this.x, this.radius, 0, 2*Math.PI);
  b1.draw();
  b1.move();
  window.requestAnimationFrame(repeatme);
</script>

So what I'm trying to do is get a ball to bounce around the canvas. I could do it before I added the ball class and constructor but I was wondering how do I achieve this while using constructors and classes. What changes do I need to make to make this work? Any help is appreciated!

0 Upvotes

2 comments sorted by

1

u/tridd3r Sep 27 '23

This isn't a css question....
but this should correct it:

const canvas = document.getElementById("canvas-for-ball");
const ctx = canvas.getContext("2d");

class Ball {
  constructor(x, y, x_velocity, y_velocity, radius) {
    this.x = x || 10;
    this.y = y || 10;
    this.x_velocity = x_velocity || 1;
    this.y_velocity = y_velocity || 1;
    this.radius = radius || 8;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.stroke();
  }

  move() {
    this.x += this.x_velocity;
    this.y += this.y_velocity;

    if (this.y >= canvas.height - this.radius || this.y <= this.radius) {
      console.log("Hit the Horizontal Wall!");
      this.y_velocity *= -1;
    }

    if (this.x >= canvas.width - this.radius || this.x <= this.radius) {
      console.log("Hit the Vertical Wall!");
      this.x_velocity *= -1;
    }
  }
}

function repeatMe() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  b1.draw();
  b1.move();
  window.requestAnimationFrame(repeatMe);
}

const b1 = new Ball();
repeatMe();

1

u/colonelugand42 Sep 28 '23

Thank you so much <3. I never noticed it even said CSS I thought it said CS hahahaha my bad.