HTML5 canvas 基本语法

2019-01-28 20:27:15刘景俊
getImageData 方法获取 ImageData 对象。请参考示例代码。

通过 ImageData 可以完成很多功能。如可以实现图像滤镜,或可以实现数学可视化 (如分形和其他特效)。下面特效实现了简单的颜色反转滤镜:

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
  pix[i  ] = 255 - pix[i  ]; // red
  pix[i+1] = 255 - pix[i+1]; // green
  pix[i+2] = 255 - pix[i+2]; // blue
  // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);

图 4 显示了使用此滤镜后的 Opera
图像 (图 3是原图)。

Example rendering of the invert color filter.

图 4: 颜色反转滤镜

文字

虽然最近的 WebKit 版本和 Firefox 3.1 nightly build 才开始支持 Text API ,为了保证文章完整性我决定仍在这里介绍文字 API 。

context 对象可以设置以下 text 属性:

font:文字字体,同属性 属性 textAlign:文字水平对齐方式。可取属性值: start, end, left,
right, center。默认值:
start. textBaseline:文字竖直对齐方式。可取属性值:top, hanging, middle,
alphabetic, ideographic, bottom。默认值:alphabetic.

有两个方法可以绘制文字: fillTextstrokeText。第一个绘制带 fillStyle 填充的文字,后者绘制只有 strokeStyle 边框的文字。两者的参数相同:要绘制的文字和文字的位置(x,y) 坐标。还有一个可选选项——最大宽度。如果需要的话,浏览器会缩减文字以让它适应指定宽度。

文字对齐属性影响文字与设置的
(x,y) 坐标的相对位置。

下面是一个在 canvas 中绘制"hello world" 文字的例子

context.fillStyle    = '#00f';
context.font         = 'italic 30px sans-serif';
context.textBaseline = 'top';
context.fillText  ('Hello world!', 0, 0);
context.font         = 'bold 30px sans-serif';
context.strokeText('Hello world!', 0, 50);

图 5 是其效果图。

Example text render.

图 5: 文字效果

阴影

目前只有 Konqueror 和 Firefox 3.1 nightly build 支持 Shadows API 。API 的属性为: