liguofeng29’s blog

個人勉強用ブログだっす。

HTML5のcanvas要素 - グラデーション

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=SJIS" />
   <title>グラデーション</title>
</head>
<body>
<h2> グラデーションサンプル </h2>
<canvas id="canvas" width="400" height="420"
    style="border:1px solid black"></canvas>
<script type="text/javascript">
   // canvas要素取得
   var canvas = document.getElementById('canvas');
   // CanvasRenderingContext2D取得
   var ctx = canvas.getContext('2d');
   ctx.save();
   // 座標移動
   ctx.translate(30, 20);
   // ライングラデーション
   lg = ctx.createLinearGradient(0, 0, 160, 80);
   // 色追加
   lg.addColorStop(0.2, "#f00");
   lg.addColorStop(0.5, "#0f0");
   lg.addColorStop(0.9, "#00f");
   // 色
   ctx.fillStyle = lg;
   // 描く
   ctx.fillRect(0, 0, 160, 80);
   // 座標システム戻す
   //ctx.restore();
   
   // 座標移動
   ctx.translate(280, 80)
   // 経路開始
   ctx.beginPath();
   // 弧描く
   ctx.arc(0, 0 , 80, 0, Math.PI * 2, true);
   ctx.closePath();
   ctx.lineWidth = 12;
   // ライングラデーション
   lg2 = ctx.createLinearGradient(-40, -40, 80, 50);
   // 色追加
   lg2.addColorStop(0.1, "#ff0");
   lg2.addColorStop(0.4, "#0ff");
   lg2.addColorStop(0.8, "#f0f");
   // 描く
   ctx.strokeStyle = lg2;
   ctx.stroke();
   ctx.restore();
   
   ctx.translate(30, 200);
   // radialグラデーション
   lg = ctx.createRadialGradient(80, 40, 5, 80, 40, 60);
   // 色追加
   lg.addColorStop(0.2, "#f00");
   lg.addColorStop(0.5, "#0f0");
   lg.addColorStop(0.9, "#00f");
   // 色
   ctx.fillStyle = lg;
   // 描く
   ctx.fillRect(0, 0, 160, 80);
   // 座標システム戻す
   ctx.restore();
   // 座標移動
   ctx.translate(280, 80)
   ctx.beginPath();
   // 弧描く
   ctx.arc(0, 0 , 80, 0, Math.PI * 2, true);
   ctx.closePath();
   ctx.lineWidth = 12;
   // radialグラデーション
   lg2 = ctx.createRadialGradient(0, 0, 5, 0, 0, 80);
   // 色追加
   lg2.addColorStop(0.1, "#ff0");
   lg2.addColorStop(0.4, "#0ff");
   lg2.addColorStop(0.8, "#f0f");
   // 描く
   ctx.fillStyle = lg2;
   ctx.fill();
   
</script>
</body>
</html>

f:id:liguofeng29:20160124201454p:plain