萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> 用JavaScript實現使用鼠標畫線的示例代碼

用JavaScript實現使用鼠標畫線的示例代碼

 

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  02 <html xmlns="http://www.w3.org/1999/xhtml">  03    04 <head>  05 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  06 <title>Untitled 1</title>  07 <style type="text/css">  08 .style1 {  09   font-size: x-small;  10 }  11 </style>  12 <script type="text/javascript">  13 /** 14   畫點 15 */   16 function makedot(x, y){  17  pointDiv = "<div style='height:1px;position:absolute;left:" + x + 18    "px;top:" + y + "px;width:1px;background:#f00;overflow:hidden'></div>";  19  return pointDiv; 20 }  21 /**  22  根據兩點坐標畫直線。  23 */  24    25 function line(x1,y1,x2,y2){  26  var slope; //斜率 27  var direction;//坐標運動方向 28  var tx = x2 - x1; 29  var ty = y2 - y1; 30  if(tx == 0 && ty == 0)return; 31  var points = ""; 32  var axis;//坐標軸上的坐標 33  if(Math.abs(tx) >= Math.abs(ty)){//在x軸上移動 34    direction = tx > 0 ? 1 : -1; 35    tx = Math.abs(tx); 36    slope = ty / tx; 37    axis = x1; 38    for(i = 0; i < tx; i ++){ 39      points += makedot(axis, y1 + i * slope); 40      axis += direction; 41    } 42        43  }else{//在y軸上移動 44    direction = ty > 0 ? 1 : -1; 45    ty = Math.abs(ty); 46    slope = tx / ty;  47    axis = y1;   48    for(i = 0; i < ty; i ++){ 49      points += makedot(x1 + i * slope, axis); 50      axis += direction; 51    } 52  } 53  var container = document.getElementById("container"); 54  container.innerHTML += points;  55 }  56 var oldPoint = null; 57 //獲取鼠標位置 58 function mousePosition(ev){ 59   ev = ev || window.event; 60   if(ev.pageX || ev.pageY){ 61     return {x:ev.pageX, y:ev.pageY}; 62   } 63   var doc = document.documentElement, body = document.body; 64   var pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); 65   var pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);     66   return {x:pageX, y:pageY}; 67 } 68    69 function recordPoint(ev){ 70      71   var point = mousePosition(ev); 72   if(oldPoint != null){
copyright © 萬盛學電腦網 all rights reserved