Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get data url of selected area #81

Open
g-akshay opened this issue Aug 6, 2015 · 1 comment
Open

Get data url of selected area #81

g-akshay opened this issue Aug 6, 2015 · 1 comment

Comments

@g-akshay
Copy link

g-akshay commented Aug 6, 2015

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

@g-akshay
Copy link
Author

g-akshay commented Aug 7, 2015

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.

@g-akshay g-akshay closed this as completed Aug 7, 2015
@g-akshay g-akshay reopened this Aug 8, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant