用 addColorStop() 方法规定不同的颜色,以及在 gradient 对象中的何处定位颜色。如: var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,170,0);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(0.5,"red");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);