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” —)。
. x$ J& [8 f# }" e ^. m在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?
" X+ B( d# s9 d: u( [& l
8 `6 R" Q$ e3 A$ _+ j6 I* Y; O以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。1 Y1 r2 \7 j1 f# o& d8 H! d7 ]
代码如下:
1 Y3 Q8 d4 e" Q. Qvar canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype;3 \" {! C" L$ ]& ^& `
canvasprototype.dottedline = function(x1, y1, x2, y2, interval) {' k% b4 F# ], [
if (!interval) {
* S( W9 t/ Z2 w( U6 dinterval = 5;. J( s5 n# b3 V8 `: P2 D$ C
}. Z+ R5 W9 W, ~6 J3 B8 [. t' s
var ishorizontal=true;$ N6 O8 X5 Q) V9 a7 z" Z- G, l* P
if (x1==x2){, U( h- Q$ [6 V1 B1 M) s/ _. {% w
ishorizontal=false;3 w k* S; A5 U1 D
}* G) O- y1 f" ]2 e _& Z( \. Z
var len = ishorizontal ? x2-x1 : y2-y1;+ {( a: {) D: ?- C8 L' X
this.moveto(x1, y1);) |- d" N: s4 B! i
var progress=0;
% i9 t9 S, ~- Cwhile (len > progress) {+ ` c d- E# ]2 K% a' r9 I
progress += interval;
8 G! V/ a+ P+ w" d3 aif (progress > len) {' O. X1 c! m6 g8 ^
progress = len;
0 A6 m1 v( P; B9 X9 z! H}5 d& \8 y$ w) [6 D
if (ishorizontal) {9 t- V6 f: g* l. p# T" a+ K
this.moveto(x1+progress,y1);
* i; v+ ?0 ?' ~- W n+ N% d+ t- g0 _this.arc(x1+progress,y1,1,0,2*math.pi,true);# q; d; e2 J0 H
this.fill();: @2 E. B# A9 ?7 ~: ]
} else {& z1 }0 F* l) q& j; ?! W4 E0 a$ g
this.moveto(x1,y1+progress);8 b/ H2 E) {& f% x
this.arc(x1,y1+progress,1,0,2*math.pi,true);
2 z+ L# _* x1 x2 y* Dthis.fill();
m8 c2 x) A4 R3 E# u}2 a2 t5 T' ]1 f3 m3 {
}# ]7 a, t% J! ]3 _" K$ [
}3 I2 Z3 j% o. x, \* T: {8 V) ^
" I6 u% E6 z9 J8 m' T: F8 N& M, [更多网页制作信息请查看: 网页制作 |
|