shadowColor:阴影颜色。其值和 CSS 颜色值一致。
shadowBlur:设置阴影模糊程度。此值越大,阴影越模糊。其效果和 Photoshop 的高斯模糊滤镜相同。
shadowOffsetX 和 shadowOffsetY:阴影的 x 和 y 偏移量,单位是像素。
下面是 canvas 阴影的例子:
context.shadowOffsetX = 5; context.shadowOffsetY = 5; context.shadowBlur = 4; context.shadowColor = 'rgba(255, 0, 0, 0.5)'; context.fillStyle = '#00f'; context.fillRect(20, 20, 150, 100);其效果见图 6。
图 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











