HTML5 Canvas 画虚线组件

    前段时间由于项目需要,用到了HTML5 Canvas画图,但是没有画虚线的方法,自己写了一个HTML5 画虚线的组件。

    dashedLine.js

 1 if (window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype.lineTo) {
 2     CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, dashArray) {
 3         if (!dashArray) dashArray = [5, 5];
 4         var dashCount = dashArray.length;
 5         this.moveTo(x, y);
 6         var dx = (x2 - x), dy = (y2 - y);
 7         var slope = dy / dx;
 8         var distRemaining = Math.sqrt(dx * dx + dy * dy);
 9         var dashIndex = 0, draw = true;
10         while (distRemaining >= 0.1 && dashIndex < 10000) {
11             var dashLength = dashArray[dashIndex++ % dashCount];
12             if (dashLength == 0) dashLength = 0.001; // Hack for Safari
13             if (dashLength > distRemaining) dashLength = distRemaining;
14             var xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
15             x += xStep
16             y += slope * xStep;
17             this[draw ? 'lineTo' : 'moveTo'](x, y);
18             distRemaining -= dashLength;
19             draw = !draw;
20         }
21         // Ensure that the last segment is closed for proper stroking
22         this.moveTo(0, 0);
23     }
24 }
25 //canvas 画布ID
26 //defaultX defaultY 起始坐标点
27 //x,y终点坐标点
28 function dashedLine(canvas, defaultX, defaultY, x, y) {
29     var c = document.getElementById(canvas);
30     var cxt = c.getContext("2d");
31     cxt.strokeStyle = 'black';
32     var dashes = "5 5";
33     var drawDashes = function () {
34         var dashGapArray = dashes.replace(/^\s+|\s+$/g, '').split(/\s+/);
35         if (!dashGapArray[0] || (dashGapArray.length == 1 && dashGapArray[0] == 0)) return;
36         cxt.lineWidth = "1";
37         cxt.lineCap = "round";
38         cxt.beginPath();
39         cxt.strokeStyle = 'red'
40         //开始画虚线。
41         cxt.dashedLine(defaultX, defaultY, x, y, dashGapArray);
42         cxt.closePath();
43         cxt.stroke();
44     };
45     drawDashes();
46 }

 

    HTML页面调用

    

 1 <!DOCTYPE HTML>
 2 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 3 <title>HTML Canvas 画虚线</title>
 4 <script type="text/javascript" src="dashedLine.js"></script>
 5 </head>
 6 <body>
 7     <canvas id="can" width="240" height="240" style="border: 1px solid #00F">浏览器不支持HTML5!</canvas>
 8     <script type="text/javascript" charset="utf-8">
 9         dashedLine("can", 20, 20, 200, 200)
10     </script>
11 </body>
12 </html>

 

    效果图

   

 

posted @ 2014-04-16 11:39  Joye.Net  阅读(2388)  评论(1编辑  收藏  举报