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” —)。2 V& V8 {8 @' V9 U2 |
在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?2 _5 B. R6 L+ j6 @
- {( E/ K N& I4 F& X) O, h以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。1 C. `5 Y* m$ T9 J; d# J( W$ Z
代码如下:" m* i6 ?) ]; L1 U
var canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype;
8 _3 H' M# G6 v0 R# ]; }. {( K9 bcanvasprototype.dottedline = function(x1, y1, x2, y2, interval) {
1 p- A1 f% l0 y/ ]% uif (!interval) {
8 R; l( g/ V: A4 ^! L' Cinterval = 5;
8 t" e9 Z* H+ a9 m$ j}
3 Z: t/ p; V$ _4 \6 U' Q @var ishorizontal=true;
+ p: c2 @: T9 y! L. b/ [! s. d/ Jif (x1==x2){. r( K, A- c, m+ x" }
ishorizontal=false;
% _- e; W. ], M0 o/ t}
) ?; C3 }% N; L- k! ]( S/ ]var len = ishorizontal ? x2-x1 : y2-y1;8 ^3 X* T/ f! A3 l
this.moveto(x1, y1);
4 M6 X# @8 O) x0 Y3 V: L" h% Q9 tvar progress=0;
1 l; ]6 [) _+ [9 b( Q0 kwhile (len > progress) {
9 Q* X# G3 P U1 Oprogress += interval;& l4 d5 Q- D" p9 A: Q; Q
if (progress > len) {3 H6 |1 L- i8 j( j, \8 s, Z! j2 j7 M! b# A
progress = len; d1 a3 E# M# e( R2 S
}7 m$ P( [( t0 C ^! a5 h
if (ishorizontal) {
: q6 Z5 A; f! d1 T4 V5 v6 ?7 |2 l/ Xthis.moveto(x1+progress,y1);
+ p' h& \3 E1 w# A, N. ?this.arc(x1+progress,y1,1,0,2*math.pi,true);# y; P: o' s% L: A7 x4 x
this.fill();8 G1 ? m( b0 ]7 s% {
} else {6 X% J; @. a% ?0 S
this.moveto(x1,y1+progress);
& q3 I3 Z1 ?3 _& U, t% ?this.arc(x1,y1+progress,1,0,2*math.pi,true);
3 Z( w2 p/ m. I6 K8 d e. sthis.fill();
6 s; M! R5 y8 t7 W/ Y}$ h6 z/ W N) [0 V/ G
}; \& ?1 U8 P* t4 s1 f
}
9 }+ G5 j' G9 k/ {9 n6 P& ^- B8 A
- C- e( N; d7 b9 n+ e更多网页制作信息请查看: 网页制作 |
|