本文翻译自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.# j1 q3 D \7 [; r) m
让我们来看一下canvas内置的简单几何图形 — 矩形的绘制。在canvas中,绘制矩形有三种方法:填充(fillrect)、描边(strokerect)以及清除(clearrect)。当然,我们也可以使用“路径”来描绘包括矩形在内的所有图形。' n, b; t6 I6 i* l9 J$ g
以下是上述三种方法的api: ?- B1 O) z- C) l% u% _: `
1.fillrect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的实心矩形。! p9 X, |( L ~! M
2.strokerect(x,y,width,height)。绘制一个从(x,y)开始,宽度为width,高度为height的矩形框。该矩形框会根据当前设置的strokestyle、linewidth、linejoin和miterlimit属性的不同而渲染成不同的样式。
* V/ o$ k- d; l) J2 S' z3.clearrect(x,y,width,height)。清除从(x,y)开始,宽度为width,高度为height的矩形区域,使之完全透明。 I/ f+ s) K6 k
在调用上述方法绘制canvas之前,我们需要设定填充和描边的样式。设定这些样式最基本的方法是使用24位色(用16进制字符串表示)。以下是一个简单的例子:
6 s! }5 m2 M' ?1 U3 B6 d$ a
* ^6 v$ L. n! S2 C- j7 ]" ^代码如下:
5 m+ M' t1 k( w6 q( o. Z6 g; Fcontext.fillstyle = #000000;
* l, D6 `8 r2 Qcontext.strokestyle = #ff00ff;" i: V6 v6 u% u1 ]2 i
在下面的例子中,填充色设定为黑色,而描边色则设定为紫色:
" [- H. T+ s7 G: ?8 F代码如下:5 s4 z- c( c2 I) b
function drawscreen() {
; x P2 s2 n$ U2 O( v) f/ w7 S, g- Ncontext.fillstyle = #000000;$ Q: i* ]0 @# C2 p) {, C0 i
context.strokestyle = #ff00ff;$ n! K4 |7 M; I: j" h# }! j; e
context.linewidth = 2;
: M: i& v. Q# n' A- Ccontext.fillrect(10, 10, 40, 40);: q; M! E+ e/ {! O( y) m- L
context.strokerect(0, 0, 60, 60);5 K0 o2 v3 \! A" h
context.clearrect(20, 20, 20, 20);% C3 ~' Z! D, b) ]5 Y
}- x9 J# }2 |2 t3 A# ]
% k* a% ^0 e5 N. I更多网页制作信息请查看: 网页制作 |