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>

 

转载于:https://www.cnblogs.com/web-fusheng/p/6906611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值