Home > Blockchain >  Jquery - Move an shape all around a transparent image
Jquery - Move an shape all around a transparent image

Time:06-29

I have an image with transparent areas. I dev another green div.

How can I move the green div all around the image by respecting the transparent areas. So the green div can pass under the transparent areas but not the non transparent one ?

Js Fiddle can be found here: https://jsfiddle.net/Lcper5y1/

function handle_mousedown(e){
    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).offset();

    function handle_dragging(e){
        var left = my_dragging.offset0.left   (e.pageX - my_dragging.pageX0);
        var top = my_dragging.offset0.top   (e.pageY - my_dragging.pageY0);
        $(my_dragging.elem)
        .offset({top: top, left: left});
    }

    function handle_mouseup(e){
        $('body')
        .off('mousemove', handle_dragging)
        .off('mouseup', handle_mouseup);
    }

    $('body')
    .on('mouseup', handle_mouseup)
    .on('mousemove', handle_dragging);
}

$('.box').mousedown(handle_mousedown);

Thanks a lot.

CodePudding user response:

    <div  style="height:100px;
        width: 100px;
        background: green;
        position: absolute; /* or relative */
        z-index: 1;">A</div>
    <img src="https://i.ibb.co/L8hb78X/Final-Apple-i-Phone-13-Skin-Cutfile-Full-Wrap-Antenna-Display.png" width="300"
      style="z-index: 2;
        position: relative;
        pointer-events: none;
        user-select: none;">

The z-index together with the position attribute is for stacking context and allows placing them above each other.

The pointer-events: none; on the img is required to click through and allow the movement of the green container.

The user-select: none; is just cosmetic.

  • Related