本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.
1 N1 C: `/ L. I! M, K# X6 S让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。
0 s; i2 C" `& Y; t' ^4 P& H8 G以下是上述三种方法的api:
: E. a, F$ F/ `& ]! u# [1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。
# I: Z2 D- u6 ~! o. A* T6 j4 l2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。) x4 K- J. z8 ?
3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。! W6 C) `+ V9 o+ U5 t
在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:6 u+ ~6 ?3 A6 `! t2 _! J' ~
) U3 @* K' r: V4 l/ a
代码如下:4 X) s( V" Y- b( c% J- ?) n
context.fillstyle = #000000;- f& f5 z; U. Z9 u9 a, m- d
context.strokestyle = #ff00ff;
* R9 f# `: ^ ~, \, S, F8 h" O4 i6 v在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:& f4 r0 W7 e l) X ~8 R& C" m
代码如下:9 ]8 [! b& r/ M6 l% ?
function drawscreen() {
7 c- Q6 ?) l# ~context.fillstyle = #000000;5 G) L6 T; X- S! x5 d/ k5 c7 @
context.strokestyle = #ff00ff;" n: m/ o% B: [3 c6 m( h2 }5 A
context.linewidth = 2;
( b' Q+ I7 Q% X/ N7 Acontext.fillrect(10, 10, 40, 40);; Y; j! f+ F+ B; Q/ h
context.strokerect(0, 0, 60, 60);
, |! u3 R* O; k$ Y4 z5 Jcontext.clearrect(20, 20, 20, 20);$ ^; y* [6 Q* c
}
+ W- W' l, P0 o4 L, [' D1 l6 X# T" W
更多网页制作信息请查看: 网页制作 |