2017-04-01 4 views
1

引数を持つコンストラクタを使用して練習し、fillStyleメソッドに起因すると思われるエラーに遭遇しました。FillStyleクエリなどですか?

私のキャンバスは空白で表示され、コンソールにエラーはありませんか?

それぞれ独自の色で5つの異なる円を作成しようとしています。

私はフィドルを作成しました:https://jsfiddle.net/kvuf7dxb/;

コードの主バルク:

var circle1; 
    var circle2; 
    var circle3; 
    var circle4; 
    var circle5; 


    function drawCircles() { 

     ctx.clearRect(0,0,w,h); 

     circle1 = new Circle(600,600,102,55); 
     circle2 = new Circle(600,600,40,10); 
     circle3 = new Circle(600,600,37,12); 
     circle4 = new Circle(600,600,280,34); 
     circle5 = new Circle(600,600,390,55); 


    } 

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

      this.show = function() { 
       ctx.beginPath(); 
       ctx.moveTo(this.x,this.y); 
       ctx.fillStyle = this.color; 
       ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true); 
       ctx.fill(); 
      }; 
     } 

Iは、すべてのサークルが同じxおよびy座標に現れることに注意です。

+0

- 更新フィドルhttps://jsfiddle.net/kvuf7dxb/1/ –

答えて

1

修正が必要ないくつかの問題があります。ここには動作するバージョンがあります。私はインターバル方式を逃し実現

var canvas = document.getElementById('stars'); 
 
var ctx = canvas.getContext('2d'); 
 
var w = window.innerWidth; 
 
var h = window.innerHeight; 
 
canvas.width = w; 
 
canvas.height = h; 
 

 
var circle1 = new Circle(20, 20, '66CC00', 55), 
 
    circle2 = new Circle(30, 30, 'FF0000', 10), 
 
    circle3 = new Circle(40, 40, '3333FF', 12), 
 
    circle4 = new Circle(50, 50, 'FFFF00', 34), 
 
    circle5 = new Circle(70, 70, 'FF9933', 55); 
 
    
 
drawCircles(); 
 

 
function drawCircles() { 
 
    ctx.clearRect(0, 0, w, h); 
 
    circle1.show(); 
 
    circle2.show(); 
 
    circle3.show(); 
 
    circle4.show(); 
 
    circle5.show(); 
 
    requestAnimationFrame(drawCircles); 
 
} 
 

 
function Circle(x, y, color, r) { 
 
    this.x = w * x/100; 
 
    this.y = h * y/100; 
 
    this.color = '#' + color; 
 
    this.r = r; 
 
    this.show = function() { 
 
     ctx.beginPath(); 
 
     ctx.fillStyle = this.color; 
 
     ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); 
 
     ctx.fill(); 
 
    }; 
 
}
body { 
 
    background: black; 
 
    overflow: hidden; 
 
}
<canvas id="stars"></canvas>

+0

オーケーKL感謝。 requestAnimationFrameが重要な理由を教えてください。 –

+0

@ BenjaminGibbs710 'requestAnimationFrame'は主にキャンバスアニメーションに使用されます。 'setInterval/setTimeout'と比較してアニメーションをレンダリングする方が優れています –

関連する問題