渐变是指填充时从一种颜色慢慢过渡到另外一种颜色。因为是渐变所以一般会至少使用两次addColorStop()来追加颜色。
1) 绘制线性渐变
var g1 = ctx.createLinearGradient(xStart,yStart,xEnd,yEnd);//创建一个渐变对象
g1.addColorStop(offset,color);//offset 是0-1之间的浮点值,颜色离开渐变起始点的偏移量。color为绘制时候使用的颜色。
g1.addColorStop(offset,color);
ctx.fillStyle = g1;
ctx.fillRect(0,0,400,300);
2) 绘制径向渐变
var g2 = ctx.createRadialGradient(xStart,yStart,raidusStart,xEnd,yEnd,raidusEnd);//创建一个渐变对象
g2.addColorStop(offset,c