Solution to drag and draw rectangles on an image in javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • achillies
    New Member
    • Apr 2007
    • 1

    Solution to drag and draw rectangles on an image in javascript

    After hours of searching and coding, i finally have a code to drag and draw rectangles on images. I got most of the code pasted below from a post almost 2 years old and did some patch work to it. Now it works with both firefox and IE7. But with IE7, it has a minor defect...but still works. I will try to post the patch as soon as i have an answer. Here you go guys
    [CODE=html]
    <HTML>
    <HEAD>
    <META http-equiv=imagetool bar content=no>
    <TITLE>

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

    </HEAD>
    <BODY>
    <img name="myImage" id="myImage" src="VK.jpg" height=400
    width=400>


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

    <SCRIPT>

    var IMG;

    function startRubber (evt) {
    if (document.all) {
    // IE
    var r = document.all.ru bberBand;
    r.style.width = 0;
    r.style.height = 0;
    r.style.pixelLe ft = event.x;
    r.style.pixelTo p = event.y;
    r.style.visibil ity = 'visible';
    IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
    }
    else if (document.getEl ementById) {
    // firefox
    evt.preventDefa ult();
    var r = document.getEle mentById('rubbe rBand');
    r.style.width = 0;
    r.style.height = 0;
    r.style.left = evt.clientX + 'px';
    r.style.top = evt.clientY + 'px';
    r.style.visibil ity = 'visible';
    r.onmouseup = stopRubber;
    }
    IMG.onmousemove = moveRubber;
    }
    function moveRubber (evt) {
    if (document.all) { // IE
    var r = document.all.ru bberBand;
    r.style.width = event.x - r.style.pixelLe ft;
    r.style.height = event.y - r.style.pixelTo p;
    }
    else if (document.getEl ementById) { // firefox
    var r = document.getEle mentById('rubbe rBand');
    r.style.width = evt.clientX - parseInt(r.styl e.left);
    r.style.height = evt.clientY - parseInt(r.styl e.top);
    }
    return false; // otherwise IE won't fire mouseup :/
    }
    function stopRubber (evt) {
    IMG.onmousemove = null;
    }

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

    IMG = document.getEle mentById('myIma ge');
    IMG.onmousedown = startRubber;
    IMG.onmouseup = stopRubber;

    </SCRIPT>
    </BODY>
    </HTML>
    [/CODE]

    -- edit by iam_clint: thanks for posting possibly put a link to an example of it in action.
  • Paul Coldrey

    #2
    To work in newer versions of Firefox where dragging back across the rectangle (to make it smaller) causes evens to flow to the "band" you want to add the following code:

    Code:
    var band =  document.getElementById('rubberBand');
    band.onmousemove = moveRubber;

    Comment

    Working...