本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.
: y) w$ i, P+ H; U$ `- C0 L: n) f让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。& {* j4 a3 [0 ^
以下是上述三种方法的api:3 m4 ]$ H7 T/ E+ X# c
1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。
% {1 ~' ^* b* ^5 \5 i/ ]2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。* o: ]* G+ E7 b8 Z( r* u
3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。# s* A$ b A9 x/ [+ P
在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:
; R: j& _9 h6 `* X4 V" @" d) `4 J' p1 I" ^ a
代码如下:8 l2 T/ d4 C9 f4 i0 j
context.fillstyle = #000000;9 t9 G/ I; {2 k
context.strokestyle = #ff00ff;
3 {8 e) z. ]$ ~在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:
9 {( z& j" I' u$ g; m# ?5 h2 c( ~代码如下:
1 w5 W0 ^" l5 O7 w5 R5 wfunction drawscreen() {
- K% i7 L2 d; V* mcontext.fillstyle = #000000;% Y* U/ [$ q+ @- W W
context.strokestyle = #ff00ff;/ U" [* R( ^" K- l( e
context.linewidth = 2;
7 d1 m8 c8 S8 D2 Qcontext.fillrect(10, 10, 40, 40);# T, y! F) f6 L9 n+ L* @3 g9 h' d
context.strokerect(0, 0, 60, 60);$ o8 ^( c- K. M- x2 R
context.clearrect(20, 20, 20, 20);
/ | j3 ]- }4 L( v# F}2 P {2 f1 t; C3 M6 p3 J8 ]
9 n4 m$ O' }# x' r1 u7 w& c更多网页制作信息请查看: 网页制作 |