Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve toDataURL string with javascript using Cropper by fengyuanchen

I'm using the brilliant Cropper by fengyuanchen (from github) and I'm stuck on one small detail. Can anybody who has used this component show me a simple line or two of javascript/jquery which will allow me to get the toDataURL string from the cropped image into a text box? I've tried all the examples from other threads but I still can't get the string

Here's my on page html:

    <div class="img-container">
      <img id="image" src="../Crop/test.jpg" alt="Picture" runat="server" />
    </div>

  <div class="col-md-3">
    <!-- <h3 class="page-header">Preview:</h3> -->
    <div class="docs-preview clearfix">
      <div class="img-preview preview-lg"></div>
      <div class="img-preview preview-md"></div>
      <div class="img-preview preview-sm"></div>
      <div class="img-preview preview-xs"></div>
    </div>

Can anybody show me what my JQuery or javascript code should look like to get the 'toDataURL' string of the cropped image? My current script and lots of variations I've tested won't work :-(

<script>
    function run() {
        var service = new CardsWCFAjax.UploadService();
        var $selector = $(".image");
        var canvas = $($selector).cropper('getCroppedCanvas');
        var image = canvas.toDataURL('image/png');
        image = canvas.replace('data:image/png;base64,', '');
        service.GetData(image, onSuccess, null, null);
    }
</script>
like image 578
FairDeveloper.uk Avatar asked Oct 16 '25 17:10

FairDeveloper.uk


1 Answers

You have this:

 var canvas = $($selector).cropper('getCroppedCanvas');

Change to:

 var canvas = $selector.cropper('getCroppedCanvas');

If the documentation is correct ( https://github.com/fengyuanchen/cropper/blob/v2.2.5/README.md#getcroppedcanvasoptions ) the returned value is a HTMLCanvasElement so it will work perfectly with:

 var canvas = $selector.cropper('getCroppedCanvas');
 var dataURL = canvas.toDataURL();

More info:

https://developer.mozilla.org/es/docs/Web/API/HTMLCanvasElement/toDataURL

like image 173
Marcos Pérez Gude Avatar answered Oct 19 '25 07:10

Marcos Pérez Gude