CreateLinearGradient() | HTML<canvas>方法
定义与用法
- createLinearGradient() 方法创建线性的渐变对象。
- 渐变可用于填充矩形、圆形、线条、文本等等。
提示:
- 请使用该对象作为 strokeStyle 或 fillStyle 属性的值。
- 请使用 addColorStop() 方法规定不同的颜色,以及在 gradient 对象中的何处定位颜色。
语法格式
context.createLinearGradient(x0,y0,x1,y1);
示例代码
<script>
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 170, 0);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
</script>
效果展示:
浏览器支持
方法 | |||||
---|---|---|---|---|---|
CreateLinearGradient() | Yes | Yes | Yes | Yes | Yes |
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 createLinearGradient() 方法。
提示:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
参数值
参数 | 描述 |
---|---|
x0 | 渐变开始点的 x 坐标 |
y0 | 渐变开始点的 y 坐标 |
x1 | 渐变结束点的 x 坐标 |
y1 | 渐变结束点的 y 坐标 |
更多实例
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 0, 170);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
</script>
效果展示:
<script>
var c = document.getElementById("myCanvas3");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "red");
grd.addColorStop(1, "white");
ctx.fillStyle = grd;
ctx.fillRect(20, 20, 150, 100);
</script>