用JavaScript實現使用滑鼠畫線的範例程式碼_javascript技巧

來源:互聯網
上載者:User
<!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=utf-8" /> <title>Untitled 1</title> <style type="text/css"> .style1 {   font-size: x-small; } </style> <script type="text/javascript"> /**  畫點*/  function makedot(x, y){  pointDiv = "<div style='height:1px;position:absolute;left:" + x +   "px;top:" + y + "px;width:1px;background:#f00;overflow:hidden'></div>";  return pointDiv;} /**  根據兩點座標畫直線。 */ function line(x1,y1,x2,y2){  var slope; //斜率 var direction;//座標運動方向 var tx = x2 - x1; var ty = y2 - y1; if(tx == 0 && ty == 0)return; var points = ""; var axis;//座標軸上的座標 if(Math.abs(tx) >= Math.abs(ty)){//在x軸上移動   direction = tx > 0 ? 1 : -1;   tx = Math.abs(tx);   slope = ty / tx;   axis = x1;   for(i = 0; i < tx; i ++){     points += makedot(axis, y1 + i * slope);     axis += direction;   }     }else{//在y軸上移動   direction = ty > 0 ? 1 : -1;   ty = Math.abs(ty);   slope = tx / ty;    axis = y1;     for(i = 0; i < ty; i ++){     points += makedot(x1 + i * slope, axis);     axis += direction;   } } var container = document.getElementById("container"); container.innerHTML += points; } var oldPoint = null;//擷取滑鼠位置function mousePosition(ev){  ev = ev || window.event;  if(ev.pageX || ev.pageY){    return {x:ev.pageX, y:ev.pageY};  }  var doc = document.documentElement, body = document.body;  var pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);  var pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);      return {x:pageX, y:pageY};}function recordPoint(ev){    var point = mousePosition(ev);  if(oldPoint != null){    line(oldPoint.x, oldPoint.y, point.x, point.y);  }  oldPoint = point;}</script></head> <body> <div id="container" style="width: 1000px; height: 600px; border:1px #bfbfbf solid;" onclick="recordPoint(event);">  </div><script type="text/javascript">   //line(19,19,22,300); </script></body> </html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.