Home   →   Blog   →   Function for Developing Image Galleries

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.

Installation

Just add file or function to your project

or

$ 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
);

demo

You can also visit this page to read more about our useful function.

Next Posts
Bd654a87439a6c2daa5fcd146f9b25ad7e1ab288 Rails Application Template for Creating Ruby-on-Rails Apps
Rails Application Template. A basic template for creating Ruby-on-Rails applications
7c5a498bcb2ed3c81303f9531c1e0f23889b54e7 GOBUTTON Plugin. Diversify the Waiting Process
Usually, people don’t like to wait and do “nothing”. However, very often it’s inevitable. That's why one needs to make this time as pleasant or at least tolerable as possible. And this is especially true when developing applications, for it's very importa
Notice Our website uses cookies, which are necessary for its functioning and required to achieve the purposes illustrated in the privacy policy. By closing this banner you agree to the use of cookies.