本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.* o m. V* h6 U' ]5 {
让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。3 [/ G& G4 q/ o1 W
以下是上述三种方法的api:
! ]) k: f4 ~& D: k' A1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。( h; ^$ r+ F/ N
2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。- W. [! {& H8 |* S3 t5 G: }
3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。$ N* ]0 p, g, k7 b' R9 l) d! @* V
在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:
2 C: [& V$ O \4 f& K( a6 H
- I% T; ~! d; H; Z代码如下:
1 i! {- j/ c% d2 s! i+ hcontext.fillstyle = #000000;
+ Z, d9 D6 j/ r0 M1 ^! Econtext.strokestyle = #ff00ff;
7 e. m$ W5 N- Q. [在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:# c1 q$ S9 g: _* }% N
代码如下:
$ B* A2 g: \3 c7 J9 @6 j$ Y5 R+ |function drawscreen() {6 M# I0 u* W, _
context.fillstyle = #000000;2 X4 G9 |2 N3 @4 S- L3 J$ C
context.strokestyle = #ff00ff;
k1 k' L$ Q' |& Q. V$ C/ E' Ocontext.linewidth = 2;
n. q4 x. N% u6 Y, V3 ^, fcontext.fillrect(10, 10, 40, 40);
0 v7 W1 a2 C7 ?& Q& q' dcontext.strokerect(0, 0, 60, 60);
& M* m- d1 X$ qcontext.clearrect(20, 20, 20, 20);
1 |- J& E0 u' e. r1 P# I& J8 D$ n}0 d: d# B4 u7 P6 O
$ A$ W1 X: n& D, d4 A3 z
更多网页制作信息请查看: 网页制作 |