<!DOCTYPE html>
<html>
<head>
<title>画橡皮筋矩形</title>
<script type="text/javascript">
var ctx;
var linew=10;
var color="rgb(255,0,0)";
var isClick;
var startx=100;//起始位置
var starty=100;//起始位置
var endx=200;//结束位置
var endy=200;//结束位置
var wid=100;//矩形宽度
var hei=100;//矩形高度
var tid;
function setstyle(w,c){
ctx.lineWidth=w;
ctx.strokeStyle=c;
}
/*获取当前鼠标位置坐标*/
function getpoint(ev){
if(ev.clientX||ev.clientX==0){
mx=ev.clientX;
my=ev.clientY;
}else if(ev.offsetX||ev.offsetX==0){
mx=ev.offsetX;
my=ev.offsetY;
}
}
/*画出矩形框*/
function drawall(){
ctx.clearRect(0,0,400,400);
setstyle(linew,color);
ctx.beginPath();
ctx.strokeRect(startx,starty,wid,hei);
ctx.stroke();
setstyle(2,"rbg(0,0,0");
ctx.strokeRect(0,0,400,400);
}
/*初始化*/
function init(){
isClick=false;
ctx=document.getElementById('canvas').getContext('2d');
drawall();
canvasl=document.getElementById('canvas');
canvasl.addEventListener("mousedown",findball,false);//
canvasl.addEventListener("mousemove",moveit,false);
canvasl.addEventListener("mouseup",finish,false);
}
/*鼠标按下,获取矩形框起始点*/
function findball(ev){
isClick=true;
document.f.lg.value="mousedown";
getpoint(ev);
startx=mx;
starty=my;
}
/*鼠标移动,添加鼠标移动时矩形慢慢变化的效果*/
function moveit(ev){
if(isClick){
document.f.lg.value="mousemove";
getpoint(ev);
endx=mx;
endy=my;
wid=endx-startx;
hei=endy-starty;
drawall();
}
}
/*鼠标抬起事件,获取矩形框结束位置并画出来 */
function finish(ev){
if(isClick){
isClick=false;
document.f.lg.value="mouseup";
getpoint(ev);
endx=mx;
endy=my;
wid=endx-startx;
hei=endy-starty;
drawall();
console.log("start("+startx+","+starty+"),end("+endx+","+endy+")");
}
}
</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="400" height="400"></canvas>
<form id="f" name="f">
LOG:<input type="text" name="lg" id="lg" value="false"/>
</form>
</body>
</html>