odyniec / imgareaselect

ImgAreaSelect is a jQuery plugin for selecting a rectangular area of an image. It allows web developers to easily implement image cropping functionality, as well as other user interface features, such as photo notes (like those on Flickr).
http://odyniec.net/projects/imgareaselect/
686 stars 197 forks source link

Get data url of selected area #81

Open g-akshay opened 9 years ago

g-akshay commented 9 years ago

How can I get data url from selected area of image? (the image to be cropped is also generated from data URL).

g-akshay commented 9 years ago

This is how I got data URL from selected area of image.

Append a canvas (which is hidden always) to the body and draw image on canvas using the data URL of existing image and the co-ordinates which you will get in onSelectEnd callback. Then get the data URL from canvas using 'canvas.toDataURL()'.

Below is the code:


onSelectEnd : function (imageObj, co_ordinates) {

    //console.log(imageObj);

    var canvasObj = $('<canvas/>').attr({
            'id' : 'cropCanvas',
            'width' : co_ordinates.width,
            'height' : co_ordinates.height
        })
        .css({
            'display' : 'none',
            /*Make block for testing*/
            'position' : 'fixed',
        }); 

    $('body').append(canvasObj);

    var canvas = document.getElementById('cropCanvas'),
          context = canvas.getContext('2d'),
          img       = new Image();

    img.src = getImageDataUrl('YOUR_IMAGE_ID');

    // img, sx, sy, swidth, sheight, x, y, width, height
    context.drawImage(img, co_ordinates.x1, co_ordinates.y1, co_ordinates.width, co_ordinates.height, 0, 0, co_ordinates.width, co_ordinates.height);

    var dataURL = canvas.toDataURL();
    // DO WHATEVER YOU WANT WITH DATA URL NOW

    $('#cropCanvas').remove(); // removing the canvas from dom
}
});

function getImageDataUrl(id) {

    var elem = $("#" + id);

    var imgUrl = elem.css('background-image');
    imgUrl = imgUrl.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');

    return imgUrl;
};

Canvas could be heavier on DOM, please suggest if anyone has a better approach.