渐变
Context对象可以通过createLinearGradient()和createRadialGradient()两个方法创建渐变对象,这两个方法的原型如下:
Object createLinearGradient(x1, y1, x2, y2);
创建一个从(x1, y1)点到(x2, y2)点的线性渐变对象。
Object createRadialGradient(x1, y1, r1, x2, y2, r2);
创建一个从以(x1, y1)点为圆心、r1为半径的圆到以(x2, y2)点为圆心、r2为半径的圆的径向渐变对象。
渐变对象创建完成之后必须使用它的addColorStop()方法来添加颜色,该方法的原型如下:
void addColorStop(position, color);
其中position表示添加颜色的位置,取值范围为[0, 1],0表示起点,1表示终点;color表示添加的颜色,取值可以是任何CSS颜色值。
渐变对象创建并配置完成之后就可以将其赋予Context对象的strokeStyle属性或者fillStyle属性,然后绘制的图形就具有了所需的渐变效果。
那咱们一起看一下下面这个例子:
<!DOCTYPE html>
<html>
<head>
<meta
charset=
"utf-8"
>
<title></title>
<style
type=
"text/css"
>
canvas
{
left
:
50
%
;
position
:
relative
;
margin-left
:
-200px
;
top
;
}
</style>
</head>
<body>
<canvas
id=
"drawDiagonal"
width=
"400"
height=
"500"
style=
"border: 1px solid #008B8B;"
></canvas>
</body>
<script
type=
"text/javascript"
>
var
canvas
=
document
.
getElementById
(
'drawDiagonal'
);
var
cd
=
canvas
.
getContext
(
'2d'
);
cd
.
save
();
cd
.
translate
(
-
10
,
350
);
cd
.
beginPath
();
cd
.
moveTo
(
0
,
0
);
cd
.
quadraticCurveTo
(
170
,
-
80
,
260
,
-
190
);
cd
.
quadraticCurveTo
(
310
,
-
250
,
410
,
-
250
);
cd
.
strokeStyle
=
'#663300'
;
cd
.
lineWidth
=
50
;
cd
.
stroke
();
cd
.
restore
();
var
lg
=
cd
.
createLinearGradient
(
80
,
220
,
240
,
200
);
//可以尝试改变这里的参数,改变不同的效果;
lg
.
addColorStop
(
0
,
'yellow'
);
lg
.
addColorStop
(
0.9
,
'#3CB371'
);
lg
.
addColorStop
(
1
,
'#2E8B57'
);
cd
.
fillStyle
=
lg
;
//把设置好的颜色值附给cd
cd
.
strokeStyle
=
'yellowgreen'
;
cd
.
lineWidth
=
4
;
cd
.
lineJoin
=
'round'
cd
.
beginPath
();
cd
.
moveTo
(
200
,
40
);
cd
.
lineTo
(
160
,
100
);
cd
.
lineTo
(
185
,
100
);
cd
.
lineTo
(
145
,
160
);
cd
.
lineTo
(
170
,
160
);
cd
.
lineTo
(
135
,
220
);
cd
.
lineTo
(
180
,
220
);
cd
.
lineTo
(
170
,
320
);
cd
.
lineTo
(
235
,
320
);
cd
.
lineTo
(
220
,
220
)
cd
.
lineTo
(
260
,
220
);
cd
.
lineTo
(
225
,
160
);
cd
.
lineTo
(
250
,
160
);
cd
.
lineTo
(
210
,
100
);
cd
.
lineTo
(
235
,
100
);
cd
.
closePath
();
cd
.
fill
();
cd
.
stroke
();
</script>
</html>
其效果如下图所示:
大家试图去尝试一下!哪里有不明白的地方可以相互交流.