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” —)。# w y8 }: R; x/ C& }
在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?0 i( c; K1 O; |; Z s- i/ f- `
) i2 ], C, P* k, B- K) S以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。
6 k5 a1 n; F6 | ?% H代码如下:9 t O& K, C- y5 e5 K9 H
var canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype;
" @3 h& ^2 }9 \% \3 qcanvasprototype.dottedline = function(x1, y1, x2, y2, interval) {. }2 J; B( j& H; ]7 g4 H% [0 x
if (!interval) {
3 ^6 k' R: ~! B0 V0 [$ T T' C! cinterval = 5;
, W9 ?& U' c D2 S7 K}+ ?4 X3 u' B# O: n: i% [5 o
var ishorizontal=true;- N1 M* A! F5 `1 k4 N# V7 X
if (x1==x2){! E( |3 x' R: ^5 R' S
ishorizontal=false;
% p$ w9 g0 a% j5 N( Q}
, D4 Y! O& @, B& Bvar len = ishorizontal ? x2-x1 : y2-y1;
2 q5 u9 k& B9 a$ M) T- `this.moveto(x1, y1);
) u7 C! }0 u U/ wvar progress=0;
# A( j% F1 O! y( h( S. Bwhile (len > progress) {
$ K+ Y8 ~/ f/ J* X8 sprogress += interval;
$ D: l7 J6 N/ Y( Y5 xif (progress > len) {
" {) A! b2 S9 h9 @) M3 Dprogress = len;
: k, W" [; Y' T! D8 r; O}
5 e. P* ~6 ]* r3 y" Xif (ishorizontal) {
% {$ O) z5 O) _+ E0 `this.moveto(x1+progress,y1);" D3 j: Z, }+ i* H
this.arc(x1+progress,y1,1,0,2*math.pi,true);6 K! y) I# _0 y, b; P1 I# _5 W
this.fill();
! K7 I3 O& R3 A$ C: f} else {
' z4 W3 f- w: }! w4 O; |this.moveto(x1,y1+progress);
- G* C4 {& v3 j7 ~9 E* [1 ithis.arc(x1,y1+progress,1,0,2*math.pi,true);
7 W1 w+ [& ~7 w- Xthis.fill();! ~# w! s) P( j6 S8 M' S
}
& g. I, E9 w4 e}/ [% I H$ M* j( t
}( @6 F* a0 V9 R( z5 R: c
" V/ V) q% I0 _5 S* z, O更多网页制作信息请查看: 网页制作 |
|