Codementor Events

4 Cool JavaScript Image Tricks

Published Mar 21, 2021
4 Cool JavaScript Image Tricks

There are many cool things you can do with JavaScript - one of them is manipulating images. JavaScript can be used to dynamically add visual elements to your page and perform many cool effects.

In this article I’ll show how to use JavaScript tricks to perform four handy image operations - adding an image to a page, preloading an image, zooming in and out, and drawing an image dynamically on the page.

JavaScript Image Tricks

Here are a few great tricks that will help you work with images in JavaScript like the pros.

1. Adding an Image

There are two ways to add an image to your page in JavaScript: using a DOM element or a data URL.

Adding an image using DOM element
You can create a DOM element of type HTMLImageElement using the Image() constructor. This means you are using JavaScript to manipulate the DOM of the page to dynamically add a new image to an existing HTML page.

The constructor has two parameters, specifying the width and height of the resulting image tag. For example, this constructor:

var newImage = new Image(500, 1500); 
newImage.src = '/images/sea.jpg';
document.body.appendChild(newImage);

Creates the following image tag:

<img width="500" height="1500" src="/images/sea.jpg">

Keep in mind that if you want to check the actual size of the image you are using, you can access the naturalWidth and naturalHeight properties of the image element.

Adding an image using data URL
Another, more elegant way to add an image to your page is to use a data URL and encode the image using Base64. This makes your code portable, because you can store all the images in a JavaScript file, with no dependence on a server to retrieve the image from.

However, adding too many images in Base64 encoding will make your JavaScript files bloated. Only use this for essential, lightweight image elements.

A data URL looks like this:

newImage.src = 'data:image/jpeg;base64,<base64string>';

2. Preloading Images

When a user visits a page, images take time to load, as the browser makes round-trips to the storage location and back. The HTML and JavaScript may have already loaded, and users will sit there waiting for the images, which isn’t a great experience.

Here is a trick that will help you preload images—for example, if users are busy logging in or performing some other action, and the next page to be displayed is a gallery page, you can preload pages in the meantime, and then they will already be loaded when the user enters the page. You can preload hundreds of images to the browser if necessary

See this code example by Chilezie Unachukwu:
css-tricks-preload.png

3. Zoom Effect

Let’s see how to allow users to zoom in and out of images on the page using simple JavaScript resizing code. You’ll need two functions:

  • zoomin()— enlarges the image size incrementally, by a certain number of pixels each time, until it reaches a defined maximum size
  • zoomout()—scales down the image by the same increment, until it reaches the original size

See this code example by Mickey Aharony:
css-tricks-zoom-inout.png
To implement these functions on a web page, you can add Zoom In and Zoom Out buttons with an onclick event calling each of these functions.

4. Using The drawImage() Method

Another way to work with images in JavaScript is to use the HTML Canvas element and the drawImage() method. This lets you use images from the page DOM and make changes to them—for example slicing them, tiling them, or adding visual elements to them. You can also draw visual elements completely from scratch.

The method has eight parameters:

  • image—accepts an HTMLImageElement. You can either create an image using JavaScript, or take an existing image from the page DOM.
  • sx—if you want to cut out a rectangle from the image, this defines the x coordinate of the top-left corner of the rectangle. If you are using the entire image, set it to 0.
  • sy—defines the y coordinate of the rectangle to extract from the source image.
  • sWidth—defines the width of the rectangle you want to take from the image.
    sHeight—height of the rectangle.
  • dx—defines where the image should appear on the resulting canvas—this will be the x coordinate of the top-left corner of the image
  • dy—y coordinate of the top left corner of the image on the resulting canvas
  • dWidth—width of the image on the canvas, if you want to resize it
  • dHeight—height of the image on the canvas

Here is an example from MDN showing how to tile a single image multiple times on a canvas.
agile.JPG

Conclusion

In this article I covered four useful JavaScript techniques you can apply to images in your web pages:

  1. Adding an image to your pages, either as a DOM element or using a data URL
  2. Preloading images while users are performing other tasks such as login
  3. Zooming in and out when a user clicks or hovers over the image
  4. Using the drawImage() method to make changes to images on the fly - slicing them into different dimensions, tiling them on the page, drawing elements on them, and more

I hope these tricks will help you make more effective use of JavaScript in your future web projects.

Discover and read more posts from Gilad David Maayan
get started
post commentsBe the first to share your opinion
Show more replies