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

Add an example of cropping the image using % #367

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,37 @@ async test() {
}
```

Cropping an image using percentCrop:

```js
function cropImage({
// the image
image,

// the height and width the resulting image
height,
width,

// options for canvas.toDataURL
type,
encoderOptions,

// the second argument passed to the onComplete callback
percentCrop,
}){
const sx = image.naturalWidth * (percentCrop.x / 100)
const sy = image.naturalHeight * (percentCrop.y / 100)
const sWidth = image.naturalWidth * (percentCrop.width / 100)
const sHeight = image.naturalHeight * (percentCrop.height / 100)
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, sx, sy, sWidth, sHeight, 0, 0, width, height)
return canvas.toDataURL(type, encoderOptions)
}
```

Some things to note:

1. [toDataURL](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) is synchronous and will block the main thread, for large images this could be for as long as a couple of seconds. We are using `toDataURL('image/jpeg')` otherwise it will default to `image/png` and the conversion will be significantly slower.
Expand Down