首頁  >  文章  >  web前端  >  實現測距的方法

實現測距的方法

一个新手
一个新手原創
2017-10-02 09:45:411928瀏覽

最近需要做一個測距來確定使用者上傳的圖片的比例尺:
點選(確定起點)—> 滑鼠移動(即時繪製起點位置到滑鼠遊標位置直線) —>再次點擊(確定距離) 實現測距的方法

具體實作
<!DOCTYPE html><html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>两点之间画折线</title>
    <style type="text/css">
        body{            
        font-size:12px;        
        }
    </style></head><body><p style="width: 900px;height: 600px; margin: 20px auto;">
    <canvas id="myCanvas" width="900" height="600" style="border:1px solid #eef;">
        Your browser does not support the HTML5 canvas tag.    </canvas></p><script>
    var startX = "",startY = ""; // 记录起始位置
    var c=document.getElementById("myCanvas");    
    var ctx=c.getContext("2d");

    c.onclick = function(e){
        if(startX == "" && startY == ""){ // 当鼠标第一次单击时,记录起始位置
            createBox(e,"tip1");
            startX = e.offsetX;
            startY = e.offsetY;
        }else{ // 当第二次单击鼠标时,绘制直线
            drawLine(e)
            createBox(e,"tip2");
            startX = "";
            startY = "";
        }
    };
    c.onmousemove = function(e){ // 已经有起始位置后,移动鼠标时,绘制起始位置到鼠标光标位置的直线
        if(startX != "" && startY != ""){
            ctx.globalCompositeOperation="copy"; // 使鼠标每次移动时重新绘制的直线覆盖掉上一次绘制的直线
            drawLine(e)
        }
    };    function drawLine(e){
        ctx.beginPath();
        ctx.moveTo(startX,startY);
        ctx.strokeStyle="#0000ff";
        ctx.lineWidth=2;
        ctx.lineTo(e.offsetX,e.offsetY);
        ctx.stroke();
        ctx.closePath();
    }    function createBox(e,id){ // 画坐标提示框
        var myp = document.createElement("p");
        myp.setAttribute("id",id);
        myp.style.position="absolute";
        myp.style.lineHeight="20px";
        myp.style.borderStyle="solid";
        myp.style.borderColor="#aaf";
        myp.style.color="#aaf";
        myp.style.borderWidth="1px";
        myp.style.height="20px";
        myp.style.padding="6px";
        myp.style.display="none";
        document.body.appendChild(myp);        
        var myhint = document.getElementById(id);
        myhint.style.display= "block";
        myhint.style.left= (e.clientX+4)+"px";
        myhint.style.top= (e.clientY+4)+"px";
        myhint.innerHTML= id+"  x坐标:"+e.clientX+",y坐标: "+e.clientY;
    }</script></body></html>

以上是實現測距的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn