2017-08-11 70 views
0

我正在嘗試沿着x軸移動圓弧,但它給出的錯誤是x未在更新函數中定義。變量未正確放置或缺少一些參考?無法使用JS在畫布中移動圓弧

代碼

<canvas id="myCanvas"></canvas> 
<script> 
    var myCanvas = document.getElementById("myCanvas"); 
    var c = myCanvas.getContext("2d"); 

    var redArc = new Circle(50, 60, 10, "red"); 
    var greenArc = new Circle(80, 60, 15, "green"); 
    var blueArc = new Circle(120, 60, 20, "blue"); 

    function Circle(x, y, radius, color) { 
     this.x = x; 
     this.y = y; 
     this.radius = radius; 
     this.color = color; 

     this.draw = function() { 
      c.beginPath(); 
      c.arc(this.x, this.y, this.radius, 0, Math.PI * 2); 
      c.fillStyle = this.color; 
      c.fill(); 
     } 

     this.update = function() { 
      redArc.x += 1; 
      greenArc.x += 1; 
      blueArc.x += 1; 
      this.draw(); 
     } 
     this.update(); 
    }   



    function animate() { 
     requestAnimationFrame(animate); 
     c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight); 
     redArc.update(); 
     greenArc.update(); 
     blueArc.update(); 
    } 

    animate(); 

如何去修復它?任何建議 謝謝!

回答

2

用以下替換您update方法:

this.update = function() { 
    this.x += 1; 
    this.draw(); 
} 

你應該使用this.x變量名。

var myCanvas = document.getElementById("myCanvas"); 
 
var c = myCanvas.getContext("2d"); 
 

 
var redArc = new Circle(50, 60, 10, "red"); 
 
var greenArc = new Circle(80, 60, 15, "green"); 
 
var blueArc = new Circle(120, 60, 20, "blue"); 
 

 
function Circle(x, y, radius, color) { 
 
    this.x = x; 
 
    this.y = y; 
 
    this.radius = radius; 
 
    this.color = color; 
 

 
    this.draw = function() { 
 
     c.beginPath(); 
 
     c.arc(this.x, this.y, this.radius, 0, Math.PI * 2); 
 
     c.fillStyle = this.color; 
 
     c.fill(); 
 
    } 
 

 
    this.update = function() { 
 
     this.x += 1; 
 
     this.draw(); 
 
    } 
 

 
    this.update(); 
 
} 
 

 
function animate() { 
 
    c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight); 
 
    redArc.update(); 
 
    greenArc.update(); 
 
    blueArc.update(); 
 
    requestAnimationFrame(animate); 
 
} 
 

 
animate();
<canvas id="myCanvas"></canvas>

+0

好了..謝謝..這工作,但涉及的變量和this.x是不是一回事?如果我在this.x或者變量x的位置上設置增量,它是否會產生影響? – tankit88

+1

創建它之前不能使用對象。 – flamelite