canvas标签createLinearGradient方法用于设置一个延参数坐标指定直线的渐变。
设置一个从橙色到黄色再到白色的渐变为填充的矩形
var c=document.getElementById("testCanvas"); var ctx=c.getContext("2d"); var mygradient=ctx.createLinearGradient(0,0,160,0); mygradient.addColorStop(0,"orange"); mygradient.addColorStop(0.5,"yellow"); mygradient.addColorStop(1,"white"); ctx.fillStyle=mygradient; ctx.fillRect(30,40,140,110);
说明字段 | 描述 |
---|---|
document.getElementById("testCanvas") | 返回文档id属性为"testCanvas"的对象 |
getContext("2d") | getContext() 返回画布上绘图的环境。getContext("2d") 返回绘制类型(2 维)的环境,未来可能会支持3维,但现在支持2维。 |
createLinearGradient(0,0,160,0) | createLinearGradient() 方法创建线性的渐变对象。渐变开始X坐标(0)Y坐标(0),渐变结束X坐标(160)Y坐标(0) |
addColorStop(0,"orange") | addColorStop() 规定渐变对象中的颜色和位置。0是位置(0.0到1.0之间),"orange"是颜色 橙色 |
addColorStop(0.5,"yellow") | 规定第二种颜色"yellow"黄色,位置在百分之50(中间位置)。 |
addColorStop(1,"white") | 规定第三种颜色"white"白色,位置在百分百(靠右位置) |
ctx.fillStyle=mygradient | fillStyle 属性定义为三种颜色的渐变颜色。 |
fillRect(30,40,140,110) | fillRect() 绘制"已填充"的矩形,绘制X坐标为30,Y坐标为40,矩形宽为140像素,矩形高为110像素。 |
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
createLinearGradient() 方法需要指定四个参数,分别表示渐变线段的开始和结束点。
该方法返回一个线性 CanvasGradient对象。想要应用这个渐变,需要把这个返回值赋值给 fillStyle 或者 strokeStyle。
context.createLinearGradient(x0,y0,x1,y1);
参数 | 描述 |
---|---|
x0 | 渐变开始点的 x 坐标 |
y0 | 渐变开始点的 y 坐标 |
x1 | 渐变结束点的 x 坐标 |
y1 | 渐变结束点的 y 坐标 |