本文實例講述了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?dot[0]:dot[2];
var top=dot[1]-dot[3]<0?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程序設計有所幫助。