Frakcool
Frakcool

Reputation: 11143

JQuery cut an image w/o cropping plugin

I am trying to show just a part of an image with JQuery, for example, from 0 - 200 px of it's width.

I have already solved this problem, so...

  1. I want to know if there's an easier way, instead of creating a div for each image and using the script each time.
  2. A way of animating it, from right to left, instead of left to right.

This is my script, any suggestion?

$("button").click(function(){
    if($('#hello2').css("opacity") != "0"){
        $('#hello2').animate({
            "width" : "0px",
            "opacity" : "0"
        });
    }
    else{
        $('#hello2').animate({
            "opacity" : "1",
            "width" : "500px"
        });
    }
});

Fiddle

Thanks in advice

Upvotes: 1

Views: 1393

Answers (2)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

You are making it way too complicated. Just control the size of the container and it is done!

function crop(ele, x1, y1, x2, y2){
   ele.animate({
        width: x2 - x1, height: y2 - y1
   }).find(">img").animate({
        top: -x1, left: -y1
   });
}

http://jsfiddle.net/DerekL/CLFTe/

Upvotes: 1

andrew
andrew

Reputation: 9583

I changed it to use the background:url() property instead of a separate div, the effect looks a little different though.

but at least now all you have to do is animate the width of the div.

$(document).ready(function () {
    $("button").click(function () {
        if ($('#img').css("width") == "100px") {
            $('#img').animate({
                "width": "300px"
            }, 'slow');
        } else {
            $('#img').animate({
                    "width": "100px"
            }, 'slow');
        }
    });
});

updated fiddle

I didn't find a 'right to left' animation :(

Upvotes: 1

Related Questions