Code Monkey home page Code Monkey logo

cropme's Introduction

Latest version NPM Downloads Package License

Cropme

Cropme is a customizable and easy to use javascript image cropper plugin.

See the demo

Features

Support:

  • Two-dimensional translation
  • Scaling
  • Free rotation
  • Rotation and scale around the image center or the viewport center
  • Multi-touch support (pinch-zoom, two finger rotation, ...)
  • Base64 and blob exportation
  • Multiple croppers

Architecture

dist/
├── cropme.css
├── cropme.min.css   (compressed)
├── cropme.js        (UMD)
└── cropme.min.js    (UMD, compressed)

Installation

npm

npm install cropme

Download

Download the project and extract it.
then put the dist/cropme.min.css and the dist/cropme.min.js in you project.

<link rel="stylesheet" href="path-to/cropme.min.css">
<script src="path-to/cropme.min.js"></script>

CDN

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cropme@latest/dist/cropme.min.css">
<script src="https://cdn.jsdelivr.net/npm/cropme@latest/dist/cropme.min.js"></script>

Usage

Syntax

new Cropme(element, options);
  • element (HTMLElement, required): *the cropper wrapping HTML element, can be a <div> or <img> tag.

  • options (Object, optional): The configuration options, see Options.

Example

Vanilla javascript

<div id="container"></div>

<script>
  var element = document.getElementById('container');
  var cropme = new Cropme(element);
  cropme.bind({
    url: 'images/naruto.jpg'
  });
</script>

<!-- or use image tag -->
<img src="images/naruto.jpg" id="myImage" />
<script>
  var element = document.getElementById('myImage');
  new Cropme(element);
</script>

JQuery

<div id="container"></div>

<script>
  var example = $('#container').cropme();
  example.cropme('bind', {
    url: 'images/naruto.jpg'
  });
</script>

<!-- or use image tag -->
<img src="images/naruto.jpg" id="myImage" />
<script>
  $('#myImage').cropme();
</script>

Options

Container

  • Target: the container of the cropper.
  • Key: container
  • Parameters:
    • width (int|string, default: 300): the outer container width
    • height (int, default: 300): the outer container height

Example

// Fixed container
container: {
  width: 500,
  height: 400
}
// responsive container
container: {
  width: '100%',
  height: 400
}

Viewport

  • Target: the part that will be cropped.
  • Key: viewport
  • Parameters:
    • width (int, default: 100): the viewport width
    • height (int, default: 100): the viewport height
    • type (string, default: square, available: circle): the viewport frame form
    • border (object): the viewport frame border
      • enable (bool, default: true): toggle the border
      • width (int, default: 2): the border width
      • color (string, unit: hex, rgba, hsl, default: #fff): the border color

Example

viewport: {
  width: 100,
  height: 100,
  type: 'circle',
  border: {
    enable: true,
    width: 2,
    color: '#fff'
  }
}

Zoom

  • Target: the image zoom options
  • Key: zoom,
  • Parameters:
    • min (number, default: 0.01): minimum zoom
    • max (number, default: 3): maximum zoom
    • enable (bool, default: true): enable or disable the zoom feature
    • mouseWheel (bool, default: true): enable or disable mouse wheel zoom
    • slider (bool, default: false): toggle the slider input

Example

zoom: {
  min: 0.01,
  max: 3,
  enable: true,
  mouseWheel: true,
  slider: false
}

Rotation

  • Target: the image rotation
  • Key: rotation
  • Parameters:
    • enable (bool, default: true): enable or disable the rotation
    • slider (bool, default: false): toggle the slider input
    • position (string, default: right, available: right, left): the slider input position

Example

rotation: {
  enable: true,
  slider: false,
  position: 'right'
}

Transform origin

  • Target: the image transform origin
  • Parameter:
    • transformOrigin (string, default: viewport,available: image, viewport)
      image: the transform origin is the image center
      viewport: the transform origin is the viewport center

Example

{
  transformOrigin: 'viewport'
}

Custom class

  • Target: the container class
  • Parameter:
    • customClass (string, default: null): the class of the container

Example

{
  customClass: 'my-custom-class'
}

Methods

bind()

Binds an image and return a promise after the image is loaded.

Arguments

The bind() method expects an Object containing:

  • url (required)
    • type: String
    • description: The url of the image to bind.
  • position
    • x: (int,the x translation coordinate).
    • y: (int,the y translation coordinate).
      The image is translated from its origin.
      If not specified, the image is centered horizontaly and verticaly.
    • scale: (float,The scale of the image, 1 is the original image size),
      If not specified, the image will takes the container's height and scale automatically.
    • angle: (int,The rotation of the image by an angle in degree around its origin).
    • origin: (object,The x and y coordonate of the image transform origin),
      if origin is set, the transformOrigin option will be override and set to viewport,
      since image option means that the transform origin is the center of the image,
      in that case origin is not required.

Example

var container = $('#container').cropme();

container.cropme('bind', {
  url: 'images/naruto.jpg',
  position: {
    x: 230,
    y: -30,
    scale: 1.3,
    angle: 35,
    origin: {
      x: 623.26,
      y: 1150
    }
  },
});

// If you want to do some changes directly after binding the image

container.cropme('bind', {
  url: 'images/naruto.jpg',
})
.then(function(){
  //example
  container.cropme('rotate')
});

rotate()

Rotate the image to the given angle.

Arguments

  • angle
    • description: The angle the image will be rotated to.
      The rotation is not relative to the current image rotation.
    • type: number
    • unit: degree

Example

var myImage = $('#myImage').cropme();

myImage.cropme('rotate', 90);

crop()

Returns a promise with the cropped image.

Arguments

As a parameter, the crop() function can receive:

  1. An Object containing:
  • type
    • type: String
    • default: base64
    • possible value: base64, blob
    • description: The image exportation format
  • width
    • type: int
    • description: The width of the output images, the height will be
      proportional.
  • scale
    • type: number
    • description: The size of the ouput, relative to the original image size.
      If scale has a value, the width get ignored.
  • mimetype
    • type: String
    • default: image/png
    • description: The output image format.
  • quality
    • type: number
    • default: 0.92 (0.80 for image/webp mimetype when output is blob).
    • description: A Number between 0 and 1 indicating image quality.
      Works only with image/jpeg or image/webp (formats that use lossy compression).
  1. A String specifying the exportation format (base64 or blob)

For more information about mimetype and quality arguments:
toBlob() and toDataURL() HTMLCanvasElement documentation.

Calling crop() without parameters returns a base64 image with the viewport size.

Example

var myImage = $('#myImage').cropme();

// string
myImage.cropme('crop', 'blob')
  .then(function(output) {
        // here you can use the blob output
  });

// object
myImage.cropme('crop', {
    type: 'base64',
    width: 800
}).then(function(output) {
        // here you can use the base64 output
});


// no parameter
myImage.cropme('crop')
    .then(function(output) {
        // here you can use the base64 output
    });

position()

Returns an object specifying the image position
When you create a new cropme you can bind the image with this position object.

Example

var myImage = $('#myImage').cropme();

var position = myImage.cropme('position');

Output: Object

{
  x: 230,
  y: -30,
  scale: 1.3,
  angle: 35,
  origin: {
    x: 623.26,
    y: 1150
  }
}

reload()

Reload the cropme instance with a new parameters

Example

var myImage = $('#myImage').cropme({
  container: {
    width: 300,
    height: 200
  }
});

myImage.cropme('reload', {
  container: {
    width: 455,
    height: 600
  },
  viewport: {
    width: 150,
    height: 240,
    border: {
      enable: true,
      width: 5,
      color: '#f00'
    }
  }
});

destroy()

Destroy the cropme instance

Example

var myImage = $('#myImage').cropme();

myImage.cropme('destroy');

Contributing

Thank you for your contribution to this project.

Installation

Fork the project then

npm install && npm run watch

cropme's People

Contributors

pellul avatar shpontex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

cropme's Issues

How to set position on init ?

HTML:
<img src="/img/photo.jpg" id="avatar" />

JS:
var avatar = $('#avatar').cropme();

How i can to set scale, x, y on page load ?

How to use position data in backend

Hi,

Is there a way to use the position data to generate the crop image inside an backend? I've tried it with PHP & Imagick but could not get the same result. Maybe its the order in which I need to apply the details (scale, rotate, crop)?

Can you provide some info on that?

Image ID delete from DOM after init

Good morning all,

I just found a little bug it seems to me. I'm on the latest version of Google Chrome, but it does the same with Safari. When initializing the cropme the image id is deleted from the DOM. You have to go through another jQuery selector for this to work.

myImage = $ ('. cropme-container> img'). cropme ();

IE Edge does not return when crop is called

Works in Chrome and Firefox and even IE Edge dev version on mac. I double checked the demo as well in edge and same result I get in my site no output returned from crop method and results in empty.

Edit: added more details

cropme - 'viewport' of undefined

when I crop an image for first time it work great. (after cropping i would destroy the cropme. )
but when I want to crop second image i would get this error

app.js?id=79f598946b8ba4ad1fb4:12442 Uncaught TypeError: Cannot read property 'viewport' of undefined
    at Cropme.createCanvas (app.js?id=79f598946b8ba4ad1fb4:12442)
    at Cropme.crop (app.js?id=79f598946b8ba4ad1fb4:12664)
    at jQuery.fn.init.jQuery.fn.cropme (app.js?id=79f598946b8ba4ad1fb4:12088)
    at HTMLButtonElement.<anonymous> (app.js?id=79f598946b8ba4ad1fb4:10234)
    at HTMLDocument.dispatch (app.js?id=79f598946b8ba4ad1fb4:20741)
    at HTMLDocument.elemData.handle (app.js?id=79f598946b8ba4ad1fb4:20545)

this is my script:

cropImage = (item) => {
    var myImage = $(item).cropme({

        "viewport": {
            "width": 200,
            "height": 200,
            "type": "circle",
            "border": {
                "width": 2,
                "enable": true,
                "color": "#fff"
            }
        },
        "zoom": {
            "enable": true,
            "mouseWheel": true,
            "slider": true
        },
        "rotation": {
            "slider": true,
            "enable": true,
            "position": "left"
        },
        "transformOrigin": "image"
    });
    var rotate = 0;
    $(document).on('click', '.rotate', function () {
        rotate = rotate + 90;
        console.log(rotate);
        myImage.cropme('rotate', rotate);
    });
    $(document).on('click', '.crop', function () {
        let resultImage = $(this).data('target');
        console.log('myImage', myImage);

        myImage.cropme('crop', {
            type: 'base64',
            width: 200
        }).then(function (output) {
            $(resultImage).attr('src', output);
            $('.base65-holder').val(output);
            setTimeout(function () {
                myImage.cropme('destroy');
            }, 200);
            $('.js--delete-user-photo').removeClass('invisible');
            $('.crop').addClass('invisible');
        });
    })
}

// I call the function after uploading the image:
reader.onload = function (e) {
  $(result).append('<img id="uploaded-photo" src='+e.target.result+' height="100">');
  if(resizable){
	  cropImage('#uploaded-photo');
  }
};

Touch zoom is expecting to find a slider

When setting zoom to enabled (default) but slider disabled (default) the zoom is breaking on mobile pinch/zoom.

It can easily be recreated by adjusting the settings on the demo to the above and testing on a mobile device.

https://shpontex.github.io/cropme/

[Error] TypeError: undefined is not an object (evaluating 'self.properties.slider.value = touches_dist / self.properties.od')

line 405 cropme.js:

self.properties.scale = self.properties.slider.value = touches_dist / self.properties.od;

License?

What is the license of this project?
thank you. great work

cropme is blocked when using Content Security Policy Header

When using Content Security Policy Header, the browser generates a page error into the console, because the script is using either eval(), new Function(), setTimeout([string], ...) or setInterval([string], ...) for evaluating strings.

image

As CSP is a common thing to use and unsafe-eval usually should not be enabled, I´d consider this a bug.

MouseWheel not working on Firefox

Hi,

I don't know if you can fix this, but the MouseWheel feature not working on Firefox. it's ok on Chrome, IE and Safari.

Thanks for your good work

Not working at all.

I tried to use this plugin but its not working.

I get below error in browser console:
cropme.min.js:10 Uncaught Error: the argument must be an object or a string

Cropme Ghosting issue

While dragging the image in the crop area, there seems to be a trail. This wasn't an issue last week, I'm not sure what's changed. It also applies to the demo.

  • Windows 10, Chrome lastest build, JQuery & Bootstrap.

crop not work ios 13.5 (cordova wkwebview)

when crop , there is no response , no error message on ios 13.5 (cordova wkwebview)
works on desktop chrome & mobile safari

Cropme123.crop({
width: 300
}).then(function(output) {
// here you can use the blob output
$("#img_cropped").attr("src",output) ;
$("#img_cropped").show() ;
//$("#img_001").hide() ;
$("#container").hide() ;

	   $("#img_cancel").show() ;
	   $("#btn_crop_pic").hide() ;
	    $("#img_zoom").hide() ;
  });

Rotation during cropping from iphone camera. OK on android device

Good morning all,

I just found a little bug it seems to me. When I make a crop of an image taken directly from the camera of my iPhone it is well oriented when selecting the area to keep (before the crop). But once the crop made, the base64 image is sent rotated by 90 °.

This works on iPhone if you use a downloaded photo for example, but it poses a problem if the photo was taken with the camera of the iPhone, either directly from the camera, or from the photo library with a photo that was taken with the camera.

It works correctly on Android devices with file sent or from the camera directly.

Do you have an idea or a lead to correct this problem please?

Changing image dpi

The crop() output seems to default the base64 image to 96dpi. I can't seem to find anything in the js file to adjust the resolution. We need to output image at 300dpi to meet the requirements.
Could you point me in the right direction on how to address this issue?

getting issue on resizing screen after destroying the "cropme instance".

Firstly I uploaded an Image and when it finally uploaded on server, I destroyed the current cropme instance, so when next time I upload new image there would be new instance created.
But when I destroy the current cropme instance and after that tried to resize the current screen (I tried dragging the element inspector) but getting error in that case and the error is like:

cropme.js:1023 Uncaught TypeError: Cannot read properties of undefined (reading 'container')
at Cropme.resize

Calling crop() in javascript

Hi there, first off all, your plugin is everything I am looking for, great work!
Sadly I cannot get the crop() function to work in pure javascript.

So far I have:
var element = document.querySelector('.crop-image');
var crp = new Cropme(element, {
...
});

var crop_btn = document.querySelector('.js-crop');
crop_btn.addEventListener('click',
crp.cropme('crop', {
type: 'base64',
width: 800
}).then(function(output) {
// here you can use the base64 output
});;
});

As soon as I hit the button, I get an error "e.cropme() is not a function". Could you please point me into the right direction?

Thanks in advance!

Why hijack the native Promise object?

I notice that this library hijacks the native Promise object and adds a wrapper over it. Can this be avoided, or is there a way or a config option to opt out of it?

Was the .on removed?

I'm looking through examples and they have a cropme.on("crop:stop"...) event. Was that removed? I'd like to be able to get at the position whenever it changes - is that possible now?

Zoom in-out not working in mobile

My cropme works perfectly in desktop, but in mobile I try to zoom it just fires the rotation event. Maybe I miss some steps or plugins. Please help, thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.