忍者ブログ

19Apr

[PR]

Posted by in

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

03Mar

Canvasの線形グラデーション

Posted by No Name Ninja in 【Graphics】Canvas

Canvasの線形グラデーションについて説明しています。

DEMO

  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  ctx.beginPath();

  /* グラデーション領域をセット */
  var grad  = ctx.createLinearGradient(0,0,400,400);

  /* グラデーション終点のオフセットと色をセット */
  grad.addColorStop(0.1,'rgb(192, 80, 77)');    // 赤
  grad.addColorStop(0.9,'rgb(128, 100, 162)');  // 紫

  /* グラデーションをfillStyleプロパティにセット */
  ctx.fillStyle = grad;

  /* 矩形を描画 */
  ctx.rect(0,0, 400,400);

  //四角形を描く
  ctx.fill();

createLinearGradientでグラデーションの方向を決めます。 この場合、左上(0,0)から右下(400,400)へグラデーションを描いてます。
addColorStopでグラデーションの色を指定します。この場合、赤から紫へ変化させてます。 第一引数のoffsetが重要です。これは開始位置です。個々の色のoffsetをずらすことでグラデーションする幅が広がります。この場合、全体(0~1)のうち0.1~0.9がグラデーションで描かれてるわけです。


円でグラデーション

DEMO

もちろん円でも適用可です。単にarcで描いてるだけ。

  var ctx = canvas.getContext('2d');

  ctx.beginPath();

  /* グラデーション領域をセット */
  var grad  = ctx.createLinearGradient(0,0,400,400);

  /* グラデーション終点のオフセットと色をセット */
  grad.addColorStop(0.1,'rgb(192, 80, 77)');    // 赤
  grad.addColorStop(0.9,'rgb(128, 100, 162)');  // 紫

  /* グラデーションをfillStyleプロパティにセット */
  ctx.fillStyle = grad;

  //円を指定。
  ctx.arc(200,200,150,0/180*Math.PI,360/180*Math.PI,true);

  //四角形を描く
  ctx.fill();
PR

Comment


Vodafone絵文字 i-mode絵文字 Ezweb絵文字