canvas标签addColorStop方法用于创建渐变对象的颜色和位置。渐变的颜色至少有两种颜色,或者两种以上的颜色。
从橙色到黄色再到白色的(三种颜色)渐变为填充的矩形
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>从橙色到黄色再到白色的渐变为填充的矩形-HTML教程www.xuandaima.com</title> </head> <body> <canvas id="testCanvas" width="290" height="160" style="border:1px solid #d3d3d3;"> 您的浏览器不支持 HTML5的canvas标签。</canvas> <script> 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); </script> </body> </html>
说明字段 | 描述 |
---|---|
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像素。 |
![]() | addColorStop() 方法与 createLinearGradient() 或 createRadialGradient() 一起使用。 |
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
context.addColorStop(stop,color);
参数 | 描述 |
---|---|
stop | 介于 0.0 与 1.0 之间的值,表示渐变中开始与结束之间的位置。 |
color | 在结束位置显示的颜色值,可以参考HTML颜色 |