Search code examples
javascriptcropper

rotate is not defined cropper.js


I am using the awesome jquery-cropper plugin from fengyuanchen.

I'm having the issue of when certain images get uploaded it rotates and it is not on the right side which I have to make the user rotate them. I will upload the image via ajax. I'm getting the error rotate is not defined which I have been stuck a couple of hours.

$('#profilePhoto').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() {
                            $("#profileImageContainer").hide();
                            $("#rotateImg").show();
                            context.canvas.height = img.height;
                            context.canvas.width  = img.width;
                            context.drawImage(img, 0, 0);
                            cropper = canvas.cropper({
                                aspectRatio: 1 / 1,
                                rotatable: true,
                            });

                            $('#btnCrop').click(function() {
                                // Get a string base 64 data url
                                var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png");
                            });

                            $('#rotateImg').click(function () {
                                cropper.cropper.rotate(90);
                            });
                        };
                        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.');
            }
        });

The main problem here is about scopes since it looks like it is not reconizing the cropper variable.

This problems surfaces because when the user upload a photo sometimes this photo rotate automatically. If I could solve this problem first without having to make the user rotate the image would be better


Solution

  • Really stupid mistake. Instead of:

    cropper.cropper().rotate(90);
    

    I should apply:

    cropper.cropper('rotate', 90);