Jquery-cropper - A jQuery plugin wrapper for Cropper.js.

Overview

jquery-cropper

Build Status Coverage Status Downloads Version

A jQuery plugin wrapper for Cropper.js.

Main

dist/
├── jquery-cropper.js        (UMD)
├── jquery-cropper.min.js    (UMD, compressed)
├── jquery-cropper.common.js (CommonJS, default)
└── jquery-cropper.esm.js    (ES Module)

Getting started

Installation

npm install jquery-cropper jquery cropperjs

Include files:

<script src="/path/to/jquery.js"></script><!-- jQuery is required -->
<script src="/path/to/cropper.js"></script><!-- Cropper.js is required -->
<link  href="/path/to/cropper.css" rel="stylesheet">
<script src="/path/to/jquery-cropper.js"></script>

Usage

Initialize with $.fn.cropper method.

<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="picture.jpg">
</div>
/* Limit image width to avoid overflow the container */
img {
  max-width: 100%; /* This rule is very important, please do not ignore this! */
}
var $image = $('#image');

$image.cropper({
  aspectRatio: 16 / 9,
  crop: function(event) {
    console.log(event.detail.x);
    console.log(event.detail.y);
    console.log(event.detail.width);
    console.log(event.detail.height);
    console.log(event.detail.rotate);
    console.log(event.detail.scaleX);
    console.log(event.detail.scaleY);
  }
});

// Get the Cropper.js instance after initialized
var cropper = $image.data('cropper');

Options

See the available options of Cropper.js.

$().cropper(options);

Methods

See the available methods of Cropper.js.

$().cropper('method', argument1, , argument2, ..., argumentN);

Events

See the available events of Cropper.js.

$().on('event', handler);

No conflict

If you have to use other plugin with the same namespace, just call the $.fn.cropper.noConflict method to revert to it.

<script src="other-plugin.js"></script>
<script src="jquery-cropper.js"></script>
<script>
  $.fn.cropper.noConflict();
  // Code that uses other plugin's "$().cropper" can follow here.
</script>

Browser support

It is the same as the browser support of Cropper.js. As a jQuery plugin, you also need to see the jQuery Browser Support.

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

Comments
  • question with ie9

    question with ie9

    I found that after component initialization in ie9, I wrote "SCRIPT5022: script block raised exception but not caught (1895) (1,13098)".The picture is loaded, but the cropping box is not loaded. Is there any problem? 3cd734a3cebc2317437c38aeb149d23 39cdb13fba79d611b1fae5a705aaa51

    opened by mabidenengma 4
  • Cannot read properties of null (reading 'toDataURL')

    Cannot read properties of null (reading 'toDataURL')

    I'm submitting a...

    
    [ X ] Bug report 
    

    Current behavior

    My script isn't working with jquery wrapper. But with only cropperjs is everything fine. I'm getting Uncaught TypeError: Cannot read properties of null (reading 'toDataURL')" error $("img").cropper('getCroppedCanvas') creates just another instance of cropper.

    Expected behavior

    Working $(element).cropper('getCroppedCanvas') function

    Minimal reproduction of the problem with instructions

    https://jsfiddle.net/2chqfwj8/

    Environment

    jquery/3.4.1 cropperjs/1.5.12 jquery-cropper/1.0.1

    opened by ilovecoding69420 3
  • Uncaught TypeError: Cannot read property 'setDefaults' of undefined

    Uncaught TypeError: Cannot read property 'setDefaults' of undefined

    I'm submitting a...

    
    [ ] Regression (a behavior that used to work and stopped working in a new release)
    [x] Bug report 
    [ ] Feature request
    [ ] Documentation issue or request
    

    Current behavior

    Chrome: I get an error: Uncaught TypeError: Cannot read property 'setDefaults' of undefined, in jquery-cropper.js:68. Firefox: I get an error: TypeError: Cropper is undefined, in jquery-cropper,js:68:5

    Expected behavior

    No error.

    Minimal reproduction of the problem with instructions

    STEPS TO REPRODUCE

    Copy/paste the following files into project: https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/dist/cropper.js https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/dist/cropper.css https://raw.githubusercontent.com/fengyuanchen/jquery-cropper/master/dist/jquery-cropper.js https://raw.githubusercontent.com/fengyuanchen/jquery-cropper/master/dist/jquery-cropper.esm.js https://raw.githubusercontent.com/fengyuanchen/jquery-cropper/master/dist/jquery-cropper.common.js

    Add to html page: head -- < link rel="stylesheet" type="text/css" href="/css/cropper.css"> body -- < script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> < script src="webroot;?>js/cropper.js"> < script src="webroot;?>js/jquery-cropper.js">

    What is the motivation / use case for changing the behavior?

    Use cropper to crop an image that gets uploaded by a user, and then save the cropped image.

    Environment

    
    jquery-cropper version: 1.0.0
    
    
    Browser:
    - [x] Chrome (desktop) version 77.0.3865.90 (Official Build) (64-bit)
    - [ ] Chrome (Android) version XX
    - [ ] Chrome (iOS) version XX
    - [x] Firefox version 69.0.2 (64-bit) (Firefox Quantum)
    - [ ] Safari (desktop) version XX
    - [ ] Safari (iOS) version XX
    - [ ] IE version XX
    - [ ] Edge version XX
    
    Others:
    jquery-min version: 3.4.1
    cropper version - 4.1.0
    also tried cropper version - 1.5.6
    
    
    opened by hoolahoop 3
  • Using double click event for submission

    Using double click event for submission

    I want to let users submit a cropped image by double clicking the image (the crop modal). I've tried everything but I can't get jquery to read the double click event. I'm assuming its being overridden by the built-in double click event for toggleDragModeOnDblclick.

    I have toggleDragModeOnDblclick:false,

    I am trying: $( ".cropper-modal" ).dblclick(function() { alert( "Handler for .dblclick() called." ); });

    But I have tried #image and various other divs but can't get anything to fire.

    opened by grabby7 3
  • jquery-cropper in modal window

    jquery-cropper in modal window

    Hello, thanks for this awesome crop component!

    I have a question - do you have an example of how to use it in the modal window instead of placing the component directly into the page?

    Thanks!

    opened by Artgit 3
  • Uncaught SyntaxError: Cannot use import statement outside a module

    Uncaught SyntaxError: Cannot use import statement outside a module

    Im getting the error

    Uncaught SyntaxError: Cannot use import statement outside a module

    import DEFAULTS from './defaults'; import TEMPLATE from './template'; import render from './render'; import preview from './preview'; import events from './events'; import handlers from './handlers'; import change from './change'; import methods from './methods'

    opened by youresoshain 2
  • how to get width and height values from select option menu?

    how to get width and height values from select option menu?

    Hello, thans for nice cropper but i have a problem.

    How can i get width and height values from dropdown. normaly if i define width and height values inside data:{ manualy it is working but, cropper width and height values not changing from select option menu.

    Here my codes .

                            <select id="bolumler" name="seolink" class="form-control form-control-sm" required>
                              <option value="">Bölüm seçiniz</option>
                              <option value="0">Serbest Kırpma</option>
                              <option value="534,304,#about">Hakkımızda</option>
                              <option value="690,530,#blog">Blog</option>
                              <option value="1194,495,#facts">Rakamsal İstatistikler</option>
                              <option value="808,608,#portfolio">Ürünler</option>
                              <option value="270,93,#clients">Referansların Logoları</option>
                              <option value="400,400,#testimonials">Müşteri Görüşleri</option>                   
                                <option value="510,400,#team">Bizim Takım/Çalışanlar</option>
                            </select>
    
          $('#bolumler').on('change', function() {
            var degerler = ( this.value );  
            var bolumlerDizi = degerler.split(',');
            genislik = bolumlerDizi[0];    
            yukseklik = bolumlerDizi[1];
      });  
    
        var options = {
            data: {
                width: genislik,
                height: yukseklik,     
            },
            aspectRatio: genislik/yukseklik,
            viewMode: 1,
            restore: false,
            guides: false,
            center: false,
            dragCrop:false,
            highlight: false,
            cropBoxMovable: true,
            cropBoxResizable: true,
            rotatable:false,
            zoomable:false,
            preview: '.img-preview',
    
            crop: function(e) {
                // $dataX.val(Math.round(e.detail.x));
                //$dataY.val(Math.round(e.detail.y));
                //$dataHeight.val(Math.round(e.detail.height));
                //$dataWidth.val(Math.round(e.detail.width));
                //$dataRotate.val(e.detail.rotate);
                //$dataScaleX.val(e.detail.scaleX);
                //$dataScaleY.val(e.detail.scaleY);
            },
               
        };
    
    opened by sanalrenk 2
  • Read image bug

    Read image bug

    hi,

    When I tested all the features of croper. I encountered an exception when opening images. Exceptions appear only if these options are enabled: rotatable: false, scalable: false,

    I have attached one of these images. You can repeat this error. Use your demo page https://fengyuanchen.github.io/jquery-cropper/

    13

    0x800a13e1 - JavaScript Runtime Error: DataView is trying to access data outside the specified buffer length

    default

    opened by MBurtsev 2
  • $.ajax is not a function

    $.ajax is not a function

    Once I get the base64 image string in the main.js file, the console throws "$.ajax is not a function" error message.

    How do you actually initialize jQuery Ajax post to server? The documentation is not clear

    opened by codiiv 2
  • Cropped image is always return as base64.

    Cropped image is always return as base64.

    Is there any way to convert cropped image format to desired or at least jpeg format? Currently, I'm getting this is in base64 and uploading is taking too much time.

    opened by areebmkareem 1
  • Base64 image always return only the first part of the image

    Base64 image always return only the first part of the image

    Hello

    i've trying to test this library by cropping the image and get the base64 src

    • the problem is always when test it and get the base64 image src and trying to view it return an issue, i don't know if that is a bug or maybe some options is missing

    example of what i have :
    image

      <div>
        <img id="image" style="width: 400px;height: 400px;" src="picture.jpg">
      </div>
    
      <script>
        var $image = $('#image');
        $image.cropper({
          aspectRatio: 16 / 9,
          crop: function (event) {
          }
        });
        console.log($image); // log the variable 
        // Get the Cropper.js instance after initialized
        var cropper = $image.data('cropper');
        console.log(cropper);
    
      </script>
    
    
      <script>
        $(document).ready(function () {
        //  console.log("ready!");
        $('#btn1').click(function () {
            // alert("The button is clicked ");
            var cropper = $image.data('cropper');
            console.log(cropper);
            var data = $('#image').cropper('getCroppedCanvas');
                console.log(data.toDataURL("image/png"));
          })
        });
      </script>
    
    opened by 5-digits 1
  • Javascript upload cropped image errors on POST with 419 (unknown status)

    Javascript upload cropped image errors on POST with 419 (unknown status)

    I'm submitting a...

    
    [ ] Regression (a behavior that used to work and stopped working in a new release)
    [X ] Bug report 
    [ ] Feature request
    [ ] Documentation issue or request
    

    Current behavior

    Returns POST url 419 (unknown error) My javascript is:

    <script>
    var canvas  = $("#canvas"),
        context = canvas.get(0).getContext("2d"),
        $result = $('#EmployeePhoto');
        $formpic = $('#formemployeephoto').attr('action');
    
    $('#fileInput').on( 'change', function(){
        if (this.files && this.files[0]) {
          if ( this.files[0].type.match(/^image\//) ) {
            var reader = new FileReader();
            reader.onload = function(evt) {
               var img = new Image();
               img.onload = function() {
                 context.canvas.height = img.height;
                 context.canvas.width  = img.width;
                 context.drawImage(img, 0, 0);
                 var cropper = canvas.cropper({
                   aspectRatio: 2 / 3,
                   preview: '.img-preview'
                 });
                 $('#btnCrop').click(function() {
                    // Get a string base 64 data url
                    var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png"); 
                    $result.attr('src', croppedImageDataURL);
                    
                    canvas.cropper('getCroppedCanvas').toBlob(function(blob) {
                        url = URL.createObjectURL(blob);
                        var reader = new FileReader();
                         reader.readAsDataURL(blob); 
                         reader.onloadend = function() {
                            var base64data = reader.result;	
    
                            $.ajax({
                                type: "POST",
                                dataType: "multipart/form-data",
                                url: $formpic,
                                data: {'XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 'image': base64data},
                                success: function(data){
                                    $modal.modal('hide');
                                    alert("success upload image");
                                }
                                ,
                                error: function () {
                                    alert('Upload error');
                                }
                            });
                        };
                    });  
                 });
               };
               img.src = evt.target.result;
    	};
            reader.readAsDataURL(this.files[0]);
          }
          else {
            alert("Invalid file type! Please select an image file.");
          }
        }
        else {
          alert('No file(s) selected.');
        }
    });
    
    1. the csrf-token looks to be correct
    2. I have checked php post size and upload size parameters are ok
    3. I have tried having dataType as "multipart/form-data" and as "Json" $formpic is is populated as the action of a form already in the page

    the report in the developer tools of chrome is: POST http://127.0.0.1:8000/hrmodule/employees/updatePhoto/3 419 (unknown status) coumn1 | column 2 --------------------|--------------- xhr.onloadend | @ main.js?attr=FIgYc-D…xdquLDTxjt9uYA:1024 XMLHttpRequest.send (async) window.XMLHttpRequest.open | @ main.js?attr=FIgYc-D…xdquLDTxjt9uYA:1030 XMLHttpRequest.open | @ javascript?v=1588355796:1215 send | @ jquery.min.js:2 ajax | @ jquery.min.js:2 reader.onloadend | @ edit:827 FileReader (async) | (anonymous)| @ edit:823

    Expected behavior

    The file successfully uploads

    Minimal reproduction of the problem with instructions

    Environment

    
    jquery-cropper version: 1.0.1
    
    
    Browser:
    - [ ] Chrome (desktop) version XX
    - [ ] Chrome (Android) version XX
    - [ ] Chrome (iOS) version XX
    - [ ] Firefox version XX
    - [ ] Safari (desktop) version XX
    - [ ] Safari (iOS) version XX
    - [ ] IE version XX
    - [ ] Edge version XX
    
    Others:
    
    
    opened by afarral 1
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Simple Cropper is a jQuery plugin which gives you ability to add cropping functionality to your web application

Simple Cropper is a jQuery plugin which gives you ability to add cropping functionality to your web application. It uses html5 canvas to create cropped images and css3, so it only works on latest browsers.

null 1 Feb 15, 2022
⚠️ [Deprecated] No longer maintained, please use https://github.com/fengyuanchen/jquery-cropper

Cropper A simple jQuery image cropping plugin. As of v4.0.0, the core code of Cropper is replaced with Cropper.js. Demo Cropper.js - JavaScript image

Fengyuan Chen 7.8k Dec 27, 2022
✂ An online image cropper for content creators

Introducing CropScore ✂️ Resolutions and aspect ratios should be the last things you worry about. About ?? CropScore is an online image cropper for co

Madza 49 Dec 30, 2022
Lightweight WebSocketServer wrapper lib using ws-wrapper to wrap connected WebSockets

ws-server-wrapper Lightweight WebSocketServer wrapper lib using ws-wrapper and ws to wrap connected WebSockets. The only dependency is ws-wrapper itse

Blake Miner 17 May 9, 2022
A jQuery plugin wrapper around Bootstrap Alerts, to create Notifications (Toasts)

bootstrap-show-notification A jQuery plugin wrapper around Bootstrap 4 Alerts, to show them as toasts (also called notifications) dynamically from Jav

Stefan Haack 10 Aug 22, 2022
A Bower wrapper for @bartaz modification to the jQuery Term Highlighting plugin.

jQuery.Highlight.js Text highlighting plugin for jQuery. Original code and documentation. Install API Examples Attribution Install How to use this plu

Ilya Radchenko 46 Dec 30, 2022
React friendly API wrapper around MapboxGL JS

react-map-gl | Docs react-map-gl is a suite of React components designed to provide a React API for Mapbox GL JS-compatible libraries. More informatio

Vis.gl 6.9k Dec 31, 2022
A tiny wrapper built around fetch with an intuitive syntax. :candy:

Wretch A tiny (~ 3Kb g-zipped) wrapper built around fetch with an intuitive syntax. f[ETCH] [WR]apper Wretch 1.7 is now live ?? ! Please check out the

Julien Elbaz 2.7k Jan 3, 2023
Modern Fetch API wrapper for simplicity.

FarFetch Class Modern Fetch API wrapper for simplicity. Install npm i @websitebeaver/far-fetch Then include it in the files you want to use it in lik

Website Beaver 53 Oct 28, 2022
db.js is a wrapper for IndexedDB to make it easier to work against

db.js db.js is a wrapper for IndexedDB to make it easier to work against, making it look more like a queryable API. Usage Add a reference to db.js in

Aaron Powell 790 Nov 28, 2022
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
Convenience wrapper for Got to interact with the GitHub API

gh-got Convenience wrapper for Got to interact with the GitHub API Unless you're already using Got, you should probably use GitHub's own @octokit/rest

Sindre Sorhus 175 Dec 25, 2022
React friendly API wrapper around MapboxGL JS

react-map-gl | Docs react-map-gl is a suite of React components designed to provide a React API for Mapbox GL JS-compatible libraries. More informatio

Vis.gl 6.9k Jan 2, 2023
A wrapper library for Jitsi Meet that adds audio spatialization, to be able to create virtual meeting rooms.

A wrapper library for Jitsi Meet that adds audio spatialization, to be able to create virtual meeting rooms.

Sean T. McBeth 1.1k Dec 27, 2022
A wrapper for abstract-leveldown compliant stores, for Node.js and browsers.

levelup Table of Contents Click to expand levelup Table of Contents Introduction Supported Platforms Usage API Special Notes levelup(db[, options[, ca

Level 4k Jan 9, 2023
❤️ JavaScript/TypeScript linter (ESLint wrapper) with great defaults

JavaScript/TypeScript linter (ESLint wrapper) with great defaults Opinionated but configurable ESLint wrapper with lots of goodies included. Enforces

XO 7k Jan 9, 2023
Native wrapper for Xbox Cloud Gaming (xbox.com/play) made with Electron

Xbox Cloud Gaming wrapper Simple native Electron wrapper for Xbox Cloud Gaming (xbox.com/play) Features Windows / Mac (intel/Apple Silicon) / Linux(?)

null 34 Dec 28, 2022
React Query wrapper for NextAuth.js session management

NextAuth.js React-Query Client @next-auth/react-query React Query wrapper for NextAuth.js session management. Overview This is an alternative client f

NextAuth.js 124 Dec 16, 2022