<!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>