canvas线性渐变与径向渐变 + 案例

●线性渐变
通过createLinearGradient()方法实现线性渐变,它返回一个对象

var grad = ctx.createLinearGradient(x0,y0,x1,y1);

x0,y0表示起点坐标;
x1,y1表示终点坐标;
通过grad对象的addColorStop()方法进行颜色设置

grad.addColorStop(offset,color);

offset: 表示设置颜色渐变的起始偏移量,其值在0-1之间;
color:颜色值;

案例:水平渐变、纵向渐变、倾斜渐变
在这里插入图片描述

<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    var grad = ctx.createLinearGradient(0,0,150,0);// 指定渐变区域,和返回一个对象 水平渐变
    grad.addColorStop (0,'#f00');// 指定颜色 红
    grad.addColorStop(0.5,'#00f'); // 绿
    grad.addColorStop(1,'#0f0');// 紫
    ctx.fillStyle = grad;// 将对象赋给fillstyle;
    ctx.rect(0,0,150,150);
    ctx.fill();
    ctx.closePath();

    ctx.beginPath();
    var grad2 = ctx.createLinearGradient(150,0,150,150);// 纵向渐变
    grad2.addColorStop(0,"red");
    grad2.addColorStop(0.5,'green');
    grad2.addColorStop(1,'blue');
    ctx.fillStyle = grad2;
    ctx.rect(200,0,150,150);
    ctx.fill();
    ctx.closePath();

    ctx.beginPath();
    var grad3 = ctx.createLinearGradient(400,0,550,150);// 倾斜渐变
    grad3.addColorStop(0,'rgb(192,80,77)');
    grad3.addColorStop(0.5,'rgb(155,187,89)');
    grad3.addColorStop(1,'rgb(128,100,162)');
    ctx.fillStyle = grad3;
    ctx.rect(400,0,150,150);
    ctx.fill();
    ctx.closePath();
   
</script>

●径向渐变

通过createRadialGradient(x0,y0,r0,x1,y1,r1),返回一个对象;

var grad = createRadialGradient(150,150,20,150150,150);
grad.addColorStop(0,'red');
grad.addColorstop(1,'blue');

x0,yo,r表示渐变开始圆的圆心坐标和半径;
x1,y1,r1表示渐变结束圆心坐标和半径。

案例
在这里插入图片描述

<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    var grad = ctx.createRadialGradient(150,150,20,150,150,150);// 创建径向渐变
    grad.addColorStop(0,'red');
    grad.addColorStop(0.5,'yellow');
    grad.addColorStop(1,'blue');
    ctx.fillStyle = grad;
    ctx.rect(0,0,300,300);
    ctx.fill();
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值