用于在图像上绘制矩形的javascript

时间:2012-02-22 14:52:00

标签: javascript image

我正在用java脚本在php上做一个项目。我尝试使用javascript在图像上绘制一个矩形。矩形可以绘制任何大小的图像的任何位置与图像大小比较并显示坐标绘制矩形。请任何人帮助我...我尝试了不同的方式.....

 <STYLE>
  #rubberBand {
  position: absolute;
   visibility: hidden;
   width: 0px; height: 0px;
  border: 2px solid red;
 }
 </STYLE>

 </HEAD>
 <BODY>
 <img name="myImage" id="myImage" src="a.jpg">


 <DIV ID="rubberBand"></DIV>

 <SCRIPT>

var IMG;

  function startRubber (evt) {
   if (document.all) {

       var r = document.all.rubberBand;
       r.style.width = 0;
       r.style.height = 0;
       r.style.pixelLeft = event.x;
      r.style.pixelTop = event.y;
      r.style.visibility = 'visible';
      IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
   }
     else if (document.getElementById) {
   // firefox
   evt.preventDefault();
    var r = document.getElementById('rubberBand');
   r.style.width = 0;
  r.style.height = 0;
   r.style.left = evt.clientX + 'px';
    r.style.top = evt.clientY + 'px';
   r.style.visibility = 'visible';
   r.onmouseup = stopRubber;
    }
    IMG.onmousemove = moveRubber;
   }
   function moveRubber (evt) {
   if (document.all) { // IE
   var r = document.all.rubberBand;
    r.style.width = event.x - r.style.pixelLeft;
  r.style.height = event.y - r.style.pixelTop;
   }
   else if (document.getElementById) { // firefox
   var r = document.getElementById('rubberBand');
   r.style.width = evt.clientX - parseInt(r.style.left);
    r.style.height = evt.clientY - parseInt(r.style.top);
   }
   return false; // otherwise IE won't fire mouseup :/
   }
  function stopRubber (evt) {
  IMG.onmousemove = null;
   }

  function cancelDragDrop()
   {
  window.event.returnValue = false;
   }

   IMG = document.getElementById('myImage');
   IMG.onmousedown = startRubber;
   IMG.onmouseup = stopRubber;

 </SCRIPT>

1 个答案:

答案 0 :(得分:3)

你需要一个包装器,这样你就可以绝对地将元素放在里面。尺寸会有所不同,具体取决于您的照片和盒子的位置。

HTML:

<div class="wrapper">
     <img src="...." />
     <div class="box"></div>
</div>

CSS:

.wrapper {
    position:relative;
}

.box {
    position:absolute;
    top:10px;
    left:10px;
    width:50px;
    height:50px;
    border:2px solid #ffffff;
    background-color:transparent
}