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” —)。
+ ~* n! w W, `( L+ e; n在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?
. V3 ~& j$ O( M9 D! E, |3 c: Y# C7 q8 G3 M
以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。
! R& W+ ~* r% `6 K8 V- j4 X代码如下:8 T/ V2 Y4 ?, ~ g
var canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype;
. F# U: A2 k1 [) b( a. C% w Zcanvasprototype.dottedline = function(x1, y1, x2, y2, interval) {
+ J8 X6 f7 y3 N( lif (!interval) {5 a l# G( c& K" g
interval = 5;* a) D3 _; z. ]
}
3 x! z4 G( y6 I8 n* Uvar ishorizontal=true;
2 U+ j- I3 r8 i3 J1 r' c0 p) tif (x1==x2){2 [/ ?; y; L; m. q
ishorizontal=false;% D* t1 n: `/ X A5 n
}
. k$ b. v+ p1 K- z4 mvar len = ishorizontal ? x2-x1 : y2-y1;
6 N/ ~$ {6 r3 \* X- nthis.moveto(x1, y1);' |& j& \ L0 M; d% f
var progress=0;
) d3 I9 a5 ^! d" z7 G. W; J# Hwhile (len > progress) {9 k9 \8 {+ t* z$ ~# Y- [0 }/ b
progress += interval;6 r. x7 q/ j+ x
if (progress > len) {5 ^! k7 i' f: b! L3 U; c# k8 k
progress = len;$ E$ Y0 g* k6 o* A0 i3 ^5 j' y9 J: u3 B
}
# A; b% Q. F; I( w _/ uif (ishorizontal) { P9 c9 j0 c8 S
this.moveto(x1+progress,y1);
8 m# ^ k* T/ H3 d ^this.arc(x1+progress,y1,1,0,2*math.pi,true);" a' F" O$ r1 W! ?3 {4 v+ y: } X2 a
this.fill();" A# D# T5 a5 m8 m7 [, [5 I
} else {
& _# h* q8 T4 ?* u, s" N! Gthis.moveto(x1,y1+progress);- N+ x1 P0 C/ g! V+ r
this.arc(x1,y1+progress,1,0,2*math.pi,true);
9 I2 x+ E" }5 {8 qthis.fill();% W9 I2 \' A* M; y; ]$ V/ L2 D' A2 j) |
}
2 ]) {& t6 |" G! N, \/ A}2 {( y1 ^6 b. I" `6 k, P/ V& X9 j
}! z# @0 x2 o6 [/ U; p
, o! _4 H3 y0 B& {% z% B更多网页制作信息请查看: 网页制作 |
|