首页 > 语言 > JavaScript > 正文

js实现两点之间画线的方法

2024-05-06 16:19:59
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了js实现两点之间画线的方法,涉及javascript图形绘制的相关技巧,需要的朋友可以参考下

本文实例讲述了js实现两点之间画线的方法。分享给大家供大家参考。具体分析如下:

最近有点无聊,琢磨了很久,想到了一消磨时间的点子,也就是做js版的连连看。

两点之间画线也只是连连看最基本功能的一部分,所以我画的线也仅是折线,而且还只能向左折,后面将根据连连看中图片位置点来确定折线的方向。

 

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  3. <html xmlns="http://www.w3.org/1999/xhtml"> 
  4. <head> 
  5. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  6. <title>两点之间画折线</title> 
  7. <style type="text/css"> 
  8. body{ 
  9. font-size:12px; 
  10. } 
  11. </style> 
  12. </head> 
  13. <script type="text/javascript"> 
  14. <!-- 
  15. var dot=new Array(); 
  16. document.onmousedown =function(a)  
  17. {  
  18. //若div存在,则删除 
  19. if(document.getElementById('line_div')){ 
  20. var clearDiv=document.getElementById("line_div"); 
  21. clearDiv.parentNode.removeChild(clearDiv); 
  22. } 
  23. //按下时创建一个事件 
  24. if(!a) a=window.event; 
  25. //获取x轴、y轴坐标 
  26. var x=a.clientX; 
  27. var y=a.clientY; 
  28. //当数组长度大于等于4时,清空数组 
  29. if(dot.length>=4) dot.splice(0,4); 
  30. //将x、y添加到数组中,数组中保存了两组坐标值,相当于页面上的A(x1,y1)、B(x2,y2)两点 
  31. dot.push(x,y); 
  32. //当数组长度为4时,画线。 
  33. if(dot.length==4){ 
  34. //计算div的长和宽 
  35. var width=Math.abs(dot[0]-dot[2]); 
  36. var height=Math.abs(dot[1]-dot[3]); 
  37. //在页面上定位div左上角的具体位置 
  38. var left=dot[0]-dot[2]<0?dot[0]:dot[2]; 
  39. var top=dot[1]-dot[3]<0?dot[1]:dot[3]; 
  40. //创建div 
  41. var div=document.createElement("div"); 
  42. div.innerHTML=' <div id="line_div" style="width:'+width+'px;height:'+height+'px;position:absolute;visibility:visible;left:'+left+'px;top:'+top+'px;border-left:1px solid #cdcdcd;border-top:1px solid #cdcdcd;"></div>'; 
  43. document.body.appendChild(div); 
  44. } 
  45. }  
  46. --> 
  47. </script> 
  48. <body> 
  49. </body> 
  50. </html> 

希望本文所述对大家的javascript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选