1.线性渐变
创建渐变样式:四个参数 开始渐变的x y坐标 和 结束渐变的x y坐标
var linear = context.createLinearGradient(0, 0, 180, 0);
添加渐变颜色
linear.addColorStop(0.5, "red");
linear.addColorStop(1, "green");
设置矩形的填充色
context.fillStyle = linear;
绘制图形 矩形
context.fillRect(0, 0, 200, 100);
实例:
<canvas id="canvas" width="500" height="500"></canvas>
<script type="text/javascript">
/** @type {HTMLCanvasElement} */
// 1.获取画布
var canvas = document.getElementById("canvas");
// 2.创建画布上下文
var context = canvas.getContext("2d");
// 3.beginPath()
context.beginPath();
// 4.设置样式
// 创建渐变对象
var linear = context.createLinearGradient(0, 0, 180, 0);
// 添加渐变颜色
linear.addColorStop(0.5, "red");
linear.addColorStop(1, "green");
//设置矩形的填充色
context.fillStyle = linear;
//绘制图形
context.fillRect(0, 0, 200, 100);
</script>
2.径向渐变
createRadialGradient(x,y,r,x1,y1,r1)
x:表示渐变的开始圆的 x 坐标
y:表示渐变的开始圆的 y 坐标
r:表示开始圆的半径
x1:表示渐变的结束圆的 x 坐标
y1:表示渐变的结束圆的 y 坐标
r1:表示结束圆的半径
<script type="text/javascript">
/** @type {HTMLCanvasElement} */
// 1.获取画布
var canvas = document.getElementById("canvas");
// 2.创建画布上下文
var context = canvas.getContext("2d");
// 3.beginPath()
context.beginPath();
// 4.设置样式
// 创建渐变对象
// /径向渐变 / /
var grd = context.createRadialGradient(300, 300, 10, 300, 300, 200);
grd.addColorStop(0.1, "yellow");
grd.addColorStop(0.5, "red");
grd.addColorStop(0.8, "blue");
grd.addColorStop(1, "green");
context.fillStyle = grd;
context.arc(300, 300, 200, 0, Math.PI * 2);
context.fill();
</script>
3.文本渐变
1、fillText( )
语法:context.fillText(text,x,y,maxWidth)
text表示需要在画布上输出的文本
x表示开始绘制文本的X轴坐标
y表示开始绘制文本的 Y轴坐标
maxWidth 表示允许的最大文本宽度,单位是像素,是一个可选值。
2、createLinearGradient( )
语法:context.createLinearGradient(x0,y0,x1,y1)
x0 表示渐变开始点的X轴坐标
y0 表示渐变开始点的Y轴坐标
x1 表示渐变结束点的X轴坐标
y1 表示渐变结束点的Y轴坐标
ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","orange");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill with gradient
ctx.fillStyle=gradient;
ctx.fillText("have a nice day ",10,100);