HTML5 canvas 基本语法

2019-01-28 20:27:15刘景俊

drawImage 方法允许在 canvas 中插入其他图像
( imgcanvas 元素) 。在 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

ImageData对象保存了图像像素值。每个对象有三个属性: width, height
datadata 属性类型为CanvasPixelArray,用于储存width*height*4个像素值。每一个像素有RGB值和透明度alpha值(其值为 0 至
255,包括alpha在内!)。像素的顺序从左至右,从上到下,按行存储。

为了更好的理解其原理,让我们来看一个例子——绘制红色矩形

// Create an ImageData object.
var imgd = context.createImageData(50,50);
var pix = imgd.data;

// Loop over each pixel 和 set a transparent red.
for (var i = 0; n = pix.length, i < n; i += 4) {
  pix[i  ] = 255; // red channel
  pix[i+3] = 127; // alpha channel
}

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

注意: 不是所有浏览器都实现了 createImageData。在支持的浏览器中,需要通过