canvas 创建颜色渐变柱状图

 

 

最终结果:

代码:

 

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    body {
      text-align: center;
    }
    canvas {
      background: #ddd;
    }
  </style>
</head>
<body>
  <h3>使用渐变对象</h3>
  <canvas id="c5" width="500" height="400"></canvas>
  <script>
    function rn(min, max){    //random number
      return Math.floor(Math.random()*(max-min)+min);
    }
    function rc(min, max){    //random color
      var r = rn(min, max);
      var g = rn(min, max);
      var b = rn(min, max);
      return `rgb(${r}, ${g}, ${b})`;
    }

    var ctx = c5.getContext('2d');
    for(var i=0; i<4; i++){
      var w = 50;
      var h = rn(50,300);
      var x = (2*i+1)*50;
      var y = 50;
      //创建渐变对象,并用于填充
      var g = ctx.createLinearGradient(x, y, x, y+h);
      g.addColorStop(0, rc(0,255));
      g.addColorStop(1, '#fff');
      ctx.fillStyle = g;

      //填充一个矩形
      ctx.fillRect(x, y, w, h);
    }

  </script>
</body>
</html>

 

posted @ 2017-05-26 00:24  快乐的咸鱼  阅读(576)  评论(0编辑  收藏  举报