2016-09-01 10 views
0

問題:キャンバスに宇宙船を描いています。 x/yを上に乗せると、宇宙船の兵器の角度と範囲(現在の砲撃/向こうの宇宙船を考慮して)を示すキャンバスに円弧を描いています。現在、決定された角度は緑色で描かれており、兵器の範囲値が許す限り広がっています。角度/円弧を描く、キャンバスで放射光で満たされていますか?

しかし、私は、精度の低下を示すために決定された弧を塗りつぶすためにグラデーションを使用したいと考えています(つまり、勾配が緑色から始まり、オレンジ色に移動し、宇宙船から離れて赤色に変わります) 。

しかし、描画された円弧上のストックctx.fill()をグラデーションで置き換える方法がわかりません。

var ship { 
    loc: {x, y}, // lets say 100, 100 
    facing: facing // lets say facing 0, i.e. straight right 
    weapons: objects (range, startArc, endArc) // lets say 50, 300, 60 -> 120 degree angle, so -60 and +60 from facing (0/360) 
} 
     for (var i = 0; i < weapon.arc.length; i++){ 
      var p1 = getPointInDirection(weapon.range, weapon.arc[i][0] + angle, pos.x, pos.y); 
      var p2 = getPointInDirection(weapon.range, weapon.arc[i][1] + angle, pos.x, pos.y) 
      var dist = getDistance({x: pos.x, y: pos.y}, p1); 
      var rad1 = degreeToRadian(weapon.arc[i][0] + angle); 
      var rad2 = degreeToRadian(weapon.arc[i][1] + angle);   

      fxCtx.beginPath();   
      fxCtx.moveTo(pos.x, pos.y); 
      fxCtx.lineTo(p1.x, p1.y); 
      fxCtx.arc(pos.x, pos.y, dist, rad1, rad2, false); 
      fxCtx.closePath(); 
      fxCtx.globalAlpha = 0.3; 
      fxCtx.fillStyle = "green"; 
      fxCtx.fill(); 
      fxCtx.globalAlpha = 1; 
} 

はそれはとてもグラジエント型のフローを使用の代わりに、それが固定され、もしそうなら、どのように色付けされている?記入/アーク/ globalalphaを交換することが可能ですかちょうど楽しみのためのアニメーション勾配でアークを埋めるために

おかげ

答えて

2

放射グラデーションを使用し、設定された色が距離の一部として停止します。

関数createRadialGradientは、x、y、開始半径、およびグラデーションの位置x、y、および終了半径の6つの数字を取ります。

グラデーションオブジェクトaddColorStop関数を使用してカラーストップを追加します。グラデーションオブジェクトのaddColorStop関数は、グラデーションの外側の部分に0を、CSSのカラー文字列にカラーを1つずつ取り入れます。 "#F00"または "rgba(200,0,0,0.5)"または "RED"

次に、グラデーションを塗りつぶしスタイルとして使用します。

var canvas = document.createElement("canvas"); 
 
document.body.appendChild(canvas); 
 
var ctx = canvas.getContext("2d"); 
 

 
function update(time) { 
 
    ctx.fillStyle = "black"; 
 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
 
    // position of zones in fractions 
 
    var posRed = 0.8 + Math.sin(time/100) * 0.091; 
 
    var posOrange = 0.5 + Math.sin(time/200) * 0.2; 
 
    var posGreen = 0.1 + Math.sin(time/300) * 0.1; 
 
    var pos = { 
 
    x: canvas.width/2, 
 
    y: canvas.height/2 
 
    }; 
 

 
    var dist = 100; 
 
    var ang1 = 2 + Math.sin(time/1000) * 0.5; 
 
    var ang2 = 4 + Math.sin(time/1300) * 0.5; 
 
    var grad = ctx.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, dist); 
 
    grad.addColorStop(0, "#0A0"); 
 
    grad.addColorStop(posGreen, "#0A0"); 
 
    grad.addColorStop(posOrange, "#F80"); 
 
    grad.addColorStop(posRed, "#F00"); 
 
    grad.addColorStop(1, "#000"); 
 

 
    ctx.fillStyle = grad; 
 
    ctx.beginPath(); 
 
    ctx.moveTo(pos.x, pos.y); 
 
    ctx.arc(pos.x, pos.y, dist, ang1, ang2); 
 
    ctx.fill(); 
 
    requestAnimationFrame(update); 
 
} 
 
requestAnimationFrame(update);

+0

神聖なたわごと。それはすごくすごいです。あなたにもっと力を与える。ありがとう。 – user431806

関連する問題