Search code examples
javascriptcssimagebackgrounddraggable

Background image clipped to draggable div


i'm trying to make this thing where i have a div with a full background image and a div on top with a container, and this div is draggable, and when dragged it shows the same image as the background but altered.

Well, something among the lines of this pen

My CSS so far:

.contain{
    position:relative;
}

#dummy{ 
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}

Solution

  • If I understand your requirements correctly, you can do this by finding the current position of the draggable object as it moves, and then using those values to set the background-position of the screen's background, giving a sort of x-ray glasses effect.

    var imageOffset = {
        top: 30,
        left: 32
    };
    
    $(function() {
        var screenHeight = $('body').height() - 300; // 300: moa height
    
        $(".screen").css('background-position', -(imageOffset.left) + 'px ' + -(screenHeight + imageOffset.top) + 'px');
    
        $(".mao").draggable({
            axis: "x",
            drag: function(event, ui) {
                $(".screen").css('background-position', -(ui.position.left + imageOffset.left) + 'px ' + -(ui.position.top + imageOffset.top) + 'px');
            }
        });
    })
    

    Example Codepen: http://codepen.io/anon/pen/JWxwzK?editors=0000

    You can also use the same piece of code to constrain the hand to the left/right boundaries of the screen. There's an example of code to do that in the official docs: http://api.jqueryui.com/draggable/#event-drag