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” —)。" m" a9 ` x) y3 k" S
在stack overflow上,phrogz提供了一个自己的画虚线的实现(),严格的说,这是一个点划线的实现(p.s. 我认为该页面上rod macdougall的简化版更好)。那么,如果需要画圆点虚线(如下图所示),应该怎么办呢?
7 q2 P# i9 x( e. i
' }% M4 Y1 T: {) m8 j0 C W5 W* G5 S以下是我自己的实现,只支持画水平的和垂直的圆点虚线,可以参考phrogz与rod macdougall的方法来添加斜线描画的功能。
) q% @ g! q5 s% \5 i3 P代码如下:
^) H8 p9 f0 E5 a7 S2 mvar canvasprototype = window.canvasrenderingcontext2d && canvasrenderingcontext2d.prototype; W4 T1 ^% g' @5 T5 d5 q! q
canvasprototype.dottedline = function(x1, y1, x2, y2, interval) {
+ a0 N2 |4 @# h9 X1 aif (!interval) {! c3 ?; S) f3 B( p
interval = 5;3 ~1 q' ~. z. a' o7 D' H
}
; c8 h/ D/ R6 b8 D9 g# avar ishorizontal=true;2 ?, N6 g* X0 e% J: P
if (x1==x2){
, Z* R+ X3 [! H1 N! L/ F) D; Bishorizontal=false;) X" G F) S+ L' j' h
}- L. L& y3 a4 Q, o0 k7 o
var len = ishorizontal ? x2-x1 : y2-y1;
9 ?% b3 X- z7 P, z# b) hthis.moveto(x1, y1);
( c" t g% ] [/ t! p6 Vvar progress=0;
. L! Z6 t. a0 r* m2 Qwhile (len > progress) {8 R! g0 e2 X- c
progress += interval;, F/ n: [. i7 N& U( ^; k( g% i( j
if (progress > len) {0 L8 T' Y% ]) t1 b: T U8 B8 |# R# g
progress = len;" O0 u- `: Z3 t% p) Q: L
}
. [( h6 W& w8 L D. J- Uif (ishorizontal) {
2 ]. y" [, F6 T H1 j5 bthis.moveto(x1+progress,y1);8 S' B( c- u' e/ F
this.arc(x1+progress,y1,1,0,2*math.pi,true);
! h* X6 ]- z3 M6 D; jthis.fill();
0 R% A( l' \% d, t+ K9 W} else {: U3 C, I0 ~9 K @
this.moveto(x1,y1+progress);% \& z" ^& R6 Q7 m
this.arc(x1,y1+progress,1,0,2*math.pi,true);' H# u6 S! @% M( E0 }. X
this.fill();
5 i8 {! R( t3 n1 Z}
" a, I4 M+ _- }4 w}
w* _0 _+ v9 D$ C; x}! A& Y. z- M& T3 O- E
" {- _6 R# H! K2 X: u1 z
更多网页制作信息请查看: 网页制作 |
|