HTML5 canvas 基本语法

2020-04-21 22:46:46易采站长站整理

context.lineTo(100, 10);
context.lineTo(10, 100);
context.lineTo(10, 10);

// Done! Now fill the shape, 和 draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();

其效果图见图2.

Triangle

图 2: 三角形

另一个较负责的例子中使用了直线、曲线和圆弧。

插入图像

drawImage
方法允许在 canvas 中插入其他图像
(
 img
canvas
元素) 。在 Opera 中可以再 canvas 中绘制 SVG 图形。此方法比较复杂,可以有3个、5个或9个参数:

3个参数:最基本的

drawImage
使用方法。一个参数指定图像位置,另两个参数设置图像在 canvas中的位置。
5个参数:中级的
drawImage
使用方法,包括上面所述3个参数,加两个参数指明插入图像宽度和高度 (如果你想改变图像大小)。
9个参数:最复杂
drawImage
杂使用方法,包含上述5个参数外,另外4个参数设置源图像中的位置和高度宽度。这些参数允许你在显示图像前动态裁剪源图像。

下面是上述三个使用方法的例子:

// Three arguments: the element, destination (x,y) coordinates.
context.drawImage(img_elem, dx, dy);

// Five arguments: the element, destination (x,y) coordinates, and destination
// width and height (if you want to resize the source image).
context.drawImage(img_elem, dx, dy, dw, dh);

// Nine arguments: the element, source (x,y) coordinates, source width and
// height (for cropping), destination (x,y) coordinates, and destination width
// and height (resize).
context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);

其效果见图3.

Example rendering of drawImage.

图 3:

drawImage
效果图。

像素级操作

2D Context API 提供了三个方法用于像素级操作:

createImageData
,
getImageData
, 和
putImageData