本文分享JS實現兩點之間畫線的方法,供有需要的朋友參考。具體分析如下:
最近有點無聊,琢磨了很久,想到一個消磨時間的點子——做JS版的連連看。
兩點之間畫線只是連連看最基本功能的一部分,所以我畫的線僅是折線,而且還只能向左折,後面將根據連連看中圖片位置點來確定折線的方向。
<!DOCTYPE html>
<html xmlns="https://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程序設計有所幫助。