最近需要做一个测距来确定用户上传的图片的比例尺:
单击(确定起点)—> 鼠标移动(实时绘制起点位置到鼠标光标位置直线) —>再次单击(确定距离)
具体实现
<!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>
<div 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>
</div>
<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 mydiv = document.createElement("div");
mydiv.setAttribute("id",id);
mydiv.style.position="absolute";
mydiv.style.lineHeight="20px";
mydiv.style.borderStyle="solid";
mydiv.style.borderColor="#aaf";
mydiv.style.color="#aaf";
mydiv.style.borderWidth="1px";
mydiv.style.height="20px";
mydiv.style.padding="6px";
mydiv.style.display="none";
document.body.appendChild(mydiv);
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>