html5 canvas 提供了很多图形绘制的函数,但是很可惜,canvas api只提供了画实线的函数(lineto),却并未提供画虚线的方法。这样的设计有时会带来很大的不便,《javascript权威指南》的作者david flanagan就认为这样的决定是有问题的,尤其是在标准的修改和实现都比较简单的情况下 (“…something that is so trivial to add to the specification and so trivial to implement… i really think you’re making a mistake here” —)。 `* e+ N$ k, `8 ]6 [" m
在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?5 m# P( P! O x& A
; Y. q/ `) H6 T+ J
以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。
# N8 F6 {9 d. K9 W0 d代码如下:9 ~- A, }+ r' _6 V
var canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype;
% `+ \. s9 Y' C+ S$ }; `canvasprototype.dottedline = function(x1, y1, x2, y2, interval) {
# y6 x. W2 s: a! ]if (!interval) {: m# K, U3 ~7 ~5 B( Z. t: r
interval = 5;6 ^( X1 z) `2 ^% t( C8 W7 H. l
}
2 s$ ]' \6 {- X2 g: dvar ishorizontal=true;
7 x5 X% v, ~- N9 b: Qif (x1==x2){2 c x# Z2 \3 ~1 `: o
ishorizontal=false;
8 m# O! C( v: A" ~* d}# ?1 D9 S( I8 i3 k- M/ D
var len = ishorizontal ? x2-x1 : y2-y1;- S, M% x. Q# T) G! ?. f
this.moveto(x1, y1);) j# b* I* b- h I
var progress=0;$ v* a, d" h, o1 r& P
while (len > progress) {' R9 J' i% h3 l$ [# Z0 Q
progress += interval;. A+ l2 k U9 i6 k( {* D: I7 ?
if (progress > len) {0 r+ t5 @5 C1 @& P u
progress = len;
* D2 R+ a) P0 \* n G}) \" k7 a% N* d, B" n" S% A
if (ishorizontal) {- m& K2 `, i# R8 q" b
this.moveto(x1+progress,y1);9 L( ^, ~$ G! C% m
this.arc(x1+progress,y1,1,0,2*math.pi,true);! C. R( c2 e$ U& w* d$ M
this.fill();) r) i8 G# Z4 L% P
} else {& N+ ?+ p! Q. [# n* A
this.moveto(x1,y1+progress);. g* R& _8 |3 O$ t* B$ f9 X
this.arc(x1,y1+progress,1,0,2*math.pi,true);
" x' ]3 Y2 c1 o: w9 u) h" Ethis.fill();
; N, U& U- S& s* M) x}* U; b9 i6 Q" L l2 v9 }
}, `# ^' K' X6 m9 ]6 E, h
}
0 ?' S: Z* s) u' s
3 j+ O; Y t$ \更多网页制作信息请查看: 网页制作 |
|