<!DOCTYPE html>
<html>
<head>
<title>画橡皮筋矩形</title>
<script type="text/javascript">
var ctx;
var linew=1;
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;
removeElementDiv("newDiv");
}
/*鼠标移动,添加鼠标移动时矩形慢慢变化的效果*/
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();
addElementDiv("parent");
ctx.clearRect(2,2,396,396);
}
}
/*动态添加矩形框*/
function addElementDiv(obj){
var parent=document.getElementById(obj);
if(!parent){return;}
//添加 div
var div = document.createElement("div");
//设置 div 属性,如 id
div.setAttribute("id", "newDiv");
div.innerHTML = "可以输入内容";
if(wid<0){
div.style.left=endx+"px";
if(hei<0){
div.style.top=endy+"px";
}else{
div.style.top=starty+"px";
}
}else{
div.style.left=startx+"px";
if(hei<0){
div.style.top=endy+"px";
}else{
div.style.top=starty+"px";
}
}
div.style.width=Math.abs(wid)+"px";
div.style.height=Math.abs(hei)+"px";
div.setAttribute("contenteditable",true);
parent.appendChild(div);
}
function removeElementDiv(el){
var child = document.getElementById(el);
if(!child){return;}
child.parentNode.removeChild(child);
}
</script>
<style type="text/css">
#parent{
position: relative;
}
#newDiv{
overflow: hidden;
border: 1px solid #000;
position: absolute;
}
</style>
</head>
<body onLoad="init();">
<div id="parent">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<form id="f" name="f">
LOG:<input type="text" name="lg" id="lg" value="false"/>
</form>
</body>
</html>