2017-03-18 63 views
1

我對JavaScript相當陌生,並且正在嘗試執行圍繞框/畫布彈跳的任務。我設法做了一次,但現在正在使用對象重新創建它,我沒有得到任何錯誤,但它不工作,我真的不知道問題是什麼。如果有人能指出我正確的方向,那就太好了,謝謝。畫布畫但沒有球。對於ctx.arc使用對象在框中創建彈跳球,不起作用

<canvas id="sCanvas" width="550" height="550" style="border: solid"> </canvas> 
<body> 

<script type="text/javascript"> 

    //variables 
    var c = document.getElementById("sCanvas"); 
    var ctx = sCanvas.getContext("2d"); 
    var cHeight = sCanvas.height; 
    var cWidth = sCanvas.width; 


    //object 


    //create the sphere object 
    class Sphere { 
     constructor(aRadius){ 
      //add properties to object 
      this.radius = (aRadius || 15); //if paramater not set then make 15 
      this.colour = "green"//"hsl"(+ 360 * Math.random() + ",50%,50%"); 
       //create propertes for xPos, yPos, speedX, speedY 
      //and assign sensible values to them either 
      //hard coded or random numbers 
      //don't forget to use the format .this as above 
      this.xPos = 30; 
      this.yPos = 30; 
      this.speedX = 2; 
      this.speedY = 5; 

     } 

     drawMe(){ 
      //method to draw itself 
      ctx.beginPath(); 
      ctx.arc(this.xPos, this.Ypos, this.radius, 0, Math.PI *2, true); 
      ctx.fillStyle = this.colour; 
      ctx.fill(); 
     } 

     //method to move itself 
     moveMe(){ 
      this.yPos += this.speedY; 
      this.xPos += this.speedX; 

      if (this.yPos > 540){ 
       //statement 
       this.speedY =- this.speedY 
      } 

      else if (this.yPos < 10){ 
       //statement 
       this.speedY =- this.speedY 
      } 

      if (this.xPos > 540){ 
       //statement 
       this.speedX =- this.speedX 
      } 

      else if (this.xPos < 10){ 
       //statement 
       this.speedX =- this.speedX 
      } 
     } 
    } 


//create a new instance if sphere - called ball 
    var ball = new Sphere(); 
    //assign a 'new' instance of 'sphere()' here. 

    //redraw the screen each time to create animation 
     function render(){ 
      //recall render() using requestAnimationFrame API 
      requestAnimationFrame(render); 
      //clear canvas 
      ctx.clearRect(0, 0, cWidth, cHeight); 
      //call the drawME method of the ball object 
      ball.drawMe(); 
      //call the moveMe method of the ball object 
      ball.moveMe(); 


     } 

    render(); //set the animation and drawing on canvas going 


</script> 
</body> 

回答

1

在你drawMe()()函數你把this.Ypos代替this.yPos你可能想使

一個變化是考慮球的大小你moveMe()方法,而不是對數字進行硬編碼。我這樣說是因爲你在構造函數中將球半徑設置爲可變大小。

如果將球的半徑改爲35,那麼當它撞擊牆壁時,它的一部分會超出框的尺寸。

〜Pat

+0

ahh謝謝,我知道這將是一個愚蠢的錯誤!對不起,如果這是浪費時間的問題! :) – fyyff

+0

不是浪費時間。幾十年來,我曾經有過許多這些拼寫錯誤。 –