
图 6: canvas 阴影效果——蓝色矩形,红色阴影
颜色渐变
除了 CSS 颜色,
fillStyle 和
strokeStyle 属性可以设置为
CanvasGradient 对象。——通过
CanvasGradient可以为线条和填充使用颜色渐变。欲创建
CanvasGradient 对象,可以使用两个方法:
createLinearGradient 和
createRadialGradient。前者创建线性颜色渐变,后者创建圆形颜色渐变。创建颜色渐变对象后,可以使用对象的
addColorStop 方法添加颜色中间值。下面的代码演示了颜色渐变使用方法:
// You need to provide the source 和 destination (x,y) coordinates
// for the gradient (from where it starts 和 where it ends).
var gradient1 = context.createLinearGradient(sx, sy, dx, dy);// Now you can add colors in your gradient.
// The first argument tells the position for the color in your gradient. The
// accepted value range is from 0 (gradient start) to 1 (gradient end).
// The second argument tells the color you want, using the CSS color format.
gradient1.addColorStop(0, '#f00'); // red
gradient1.addColorStop(0.5, '#ff0'); // yellow
gradient1.addColorStop(1, '#00f'); // blue
// For the radial gradient you also need to provide source
// 和 destination circle radius.
// The (x,y) coordinates define the circle center points (start 和
// destination).
var gradient2 = context.createRadialGradient(sx, sy, sr, dx, dy, dr);
// Adding colors to a radial gradient is the same as adding colors to linear
// gradients.
我也准备了一个更复杂的例子,使用了线性颜色渐变、阴影和文字。其效果见图 7。

图 7: 使用线性颜色渐变的例子
canvas 演示
如果你想知道使用 Canvas可以做些什么,可以参看以下的工程:
Opera Widget:
SimAquarium
Artist’s
Sketchbook
Spirograph
在线工程和演示
Newton polynomial
Canvascape – "3D Walker"
Paint.Web – painting









