Home  >  Article  >  Web Front-end  >  js实现两点之间画线的方法_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 15:59:432329browse

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

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

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>两点之间画折线</title>
<style type="text/css">
body{
 font-size:12px;
}
</style>
</head>
<script type="text/javascript">
<!--
var dot=new Array();
document.onmousedown =function(a) 
{ 
 //若div存在,则删除
 if(document.getElementById('line_div')){
 var clearDiv=document.getElementById("line_div");
 clearDiv.parentNode.removeChild(clearDiv);
 }
 //按下时创建一个事件
 if(!a) a=window.event;
 //获取x轴、y轴坐标
 var x=a.clientX;
 var y=a.clientY;
 //当数组长度大于等于4时,清空数组
 if(dot.length>=4) dot.splice(0,4);
 //将x、y添加到数组中,数组中保存了两组坐标值,相当于页面上的A(x1,y1)、B(x2,y2)两点
 dot.push(x,y);
 //当数组长度为4时,画线。
 if(dot.length==4){
 //计算div的长和宽
 var width=Math.abs(dot[0]-dot[2]);
 var height=Math.abs(dot[1]-dot[3]);
 //在页面上定位div左上角的具体位置
 var left=dot[0]-dot[2]<0&#63;dot[0]:dot[2];
 var top=dot[1]-dot[3]<0&#63;dot[1]:dot[3];
 //创建div
 var div=document.createElement("div");
 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>';
 document.body.appendChild(div);
 }
} 
-->
</script>
<body>
</body>
</html>

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn