Function for Developing Image Galleries
Today, we'd like to offer web developers a simple but useful function aimed to simplify their work process. This function helps calculate image size and position for fitting canvas elements. It has been written for our own needs, but we are sure that you'll find a practical use for it too.
When can we use it?
Our function will be very useful for developing image galleries for various sites, for example, when designing a portfolio or other original and expressive photo gallery.
As you know, these galleries often require images of a defined size and even proportions. However, users rarely bother to find the right picture uploading the first one they liked. As a result, we get either a clipped image or a distorted one.
Our function named Canvas image cover position helps avoid this problem. The function recalculates the parameters of the image and aligns it in the center cutting off all unnecessary elements.
How does it work?
So, as we said, this method is helpful for calculating image position for fitting canvas elements. A behavior is the same as CSS property 'background-size: cover;'
canvasImageCoverPosition ( imageNaturalWidth, imageNaturalHeight, canvasWidth, canvasHeight, [offsetLeft, offsetTop] )
If the offsets are not specified, the image is centered.
Just add file or function to your project
$ npm install @agilie/canvas-image-cover-position
How to use
var imagePosition = canvasImageCoverPosition( image.naturalWidth, image.NaturalHeight, canvas.width, canvas.height, 0.5, 0.5 ) canvas.getContext('2d').drawImage( image, imagePosition.offsetLeft, imagePosition.offsetTop, imagePosition.width, imagePosition.height );
You can also visit this page to read more about our useful function.