HTML5 Convas APIs方法详解

2020-04-24 18:53:51易采站长站整理

☆ context.strokeRect(x, y, width, height)

在(x, y)处绘制宽和长为(width, height)的矩形轮廓。

☆ context.clearRect(x, y, width, height)

清理位置(矩形的左上角)在(x, y,),大小为(width, height)
的矩形区域。
Remove any content from the rectangular area and reset it
to its original, transparent color.
The ability to clear rectangles in the canvas is core to
creating animations and games using the HTML5 Canvas API. By
repeatedly drawing and clearing sections of the canvas, it
is possible to present the illusion of animation, and many
examples of this already exist on the Web. However, to
create animations that perform smoothly, you will need to
utilize clipping features and perhaps even a secondary
buffered canvas to minimize the flickering caused by
frequent canvas clears.

☆ context.drawImage( )

该方法有三个重载,可将图像绘制在canvas上。图像来源可以是
页面中的img标记、JS中的image对象和video的一帧。
•context.drawImage(img, x, y)
在(x, y)处用图像img绘制图像。当canvas的大小大于图像时
,整个图像被绘制;当图像大于canvas时,多余的部分被裁剪。
•context.drawImage(img, x, y, w, h)
在(x, y)处用图像img绘制长和宽为(w, h)的矩形区域。图像
的大小将改变为(w, h)。
•context.drawImage(img, imgx, imgy, imgw, imgh, cx, cy,
cw, ch)
将一个img图像作为绘制对象,裁剪img上位置为(imgx, imgy
)大小为(imgw, imgh)的区域,绘制在canvas内位置为(cx, cy)
处绘制大小为(cw, ch)的区域。
如果图像上裁剪区域超出了图像范围,则会引发异常。
•context.drawImage(video, vx, vy, vw, vh, cx, cy, cw, ch)
将一个video对象作为绘制对象,抓取video上位置为(vx, vy
)大小为(vw, vh)的一帧,在canvas上位置为(cx, cy)处绘制大
小为(cw, ch)的区域。
此外,drawImage()的第一个参数也可以是另一个 canvas。

☆ context.getImageData(x, y, width, height)

该方法从canvas内位置为(x, y)处,获得大小(width, height)
一块像素区域,返回值为一个ImageData对象。ImageData有width,
height和data三个属性。
data属性是一个像素数组,数组中每连续的四个元素代表一个像
素,四个连续元素依次含有RGBA的颜色与透明度信息。四个连续的元
素必须属于一个像素,第一个元素的位置不是随意取的。
像素数组是按照从上到下,从左到右的顺序在canvas中指定区域
扫描获取。像素数组的元素个数为width * height * 4。要获得特定
位置的像素信息。
使用了该方法的Web页面若用浏览器以本地文件方式打开不会正常
工作,通常会产生安全错误(security error)。可以将文件上传至