本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.4 a0 J2 N+ M- E. a3 V% }) ?0 a
让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。2 H \" t. K, y& Y+ c3 o' r
以下是上述三种方法的api:2 B* v6 @9 I2 o, |1 |
1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。% a+ G) n9 h6 e4 B+ d9 ]
2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。1 m; r7 G) D. q1 @9 W
3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。& R$ ?! z9 E P2 R& ~
在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:. l' ?3 g' P# r
: C2 h3 }" c4 z& b8 j4 ~
代码如下:8 `# p, l8 ]; ^$ N- E
context.fillstyle = #000000;" l' q; V7 \2 G9 }# i" L! E, u
context.strokestyle = #ff00ff;% }' x ?$ V2 @( V
在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:
& T1 u8 z; G7 ~. E, a, Q* X代码如下:) W2 W% R u8 S* i6 E2 R4 |) P2 ?
function drawscreen() { F( a/ q( n4 V& O3 |6 l; {- u9 U
context.fillstyle = #000000;
, V A: B! a! z. j2 bcontext.strokestyle = #ff00ff;
; S2 f' C; P( J. O2 Vcontext.linewidth = 2;
9 k" a2 c8 \# T/ `& s4 A/ Pcontext.fillrect(10, 10, 40, 40);4 |& p# t4 ~: e U5 \3 x
context.strokerect(0, 0, 60, 60);3 B) ^% k" O2 h% J9 K
context.clearrect(20, 20, 20, 20);
1 ?2 L: s( G3 q. S+ z3 D}
2 F* G' ^1 R. O- _) N+ ? a: K* {1 a b8 z4 W g3 o6 r8 b) `
更多网页制作信息请查看: 网页制作 |