本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.; f; _" Z7 z+ ]+ S# ~
让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。9 ?) n4 j. r* m+ U- A9 y6 R+ c3 s% N
以下是上述三种方法的api:
3 u9 m" i+ f$ U2 n: v% l1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。4 F' v, c# l; p5 @. c; k
2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。
' h9 P- I, p/ G o+ g ]/ k3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。
5 t- M! A7 @- T: T) }, l: k在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:
h" k1 W2 R3 H6 S9 z% A
' I' _+ e, ]; t0 P/ t3 x代码如下:
, V1 |- E4 G" u q7 Q+ ycontext.fillstyle = #000000;1 [4 C; U1 w/ _' m, l4 V- ^
context.strokestyle = #ff00ff;
; z5 N' a* F7 n5 ]5 B# S# w在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:
( M- w( ^" N0 Q2 ]( H代码如下:/ j( M$ U: i; g, P7 v
function drawscreen() {) w# h A. {' q. y
context.fillstyle = #000000;
# j7 E1 B) ?/ [$ f: W. U& j1 Wcontext.strokestyle = #ff00ff;0 V" V ]: {) A, F! |' O
context.linewidth = 2;
T- V- r) \" ]7 Ccontext.fillrect(10, 10, 40, 40);
: s5 J/ [( _" Y; j3 ]context.strokerect(0, 0, 60, 60);
7 C5 @/ ~( c, |0 Fcontext.clearrect(20, 20, 20, 20);2 Q) D' h- g- c6 t/ \$ R. ^
}
3 q8 N6 [$ q' [& n' U0 }; D" U2 g ?1 W; R
更多网页制作信息请查看: 网页制作 |