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>
效果图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?