- Create Image Elements in JavaScript
- Show Image in Plain HTML
- Set Src Attribute in JavaScript
- Set Multiple Src Attributes in JavaScript
- Create Image Element in JavaScript
- Add Inline Style to the Image in JavaScript
- Add ID Attribute to the Image in JavaScript
- Add Class Attribute to the Image in JavaScript
- HTMLImageElement: Image() constructor
- Syntax
- Parameters
- Usage note
- Examples
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Javascript image class api
- HTML DOM Image Object
- Example
- Create an Image Object
- Example
- Image Object Properties
- Standard Properties and Events
Create Image Elements in JavaScript
In this JavaScript tutorial, you’re going to learn 14 common scenarios you’ll probably run into, if you have not already when working with images.
Show Image in Plain HTML
img src="https://picsum.photos/200/300" />
As you can see, I use the picsum website for demonstration purposes. It lets me get a random image URL with specific dimensions passed at the end of the URL.
Set Src Attribute in JavaScript
const img = document.querySelector("img"); img.src = "https://picsum.photos/200/301";
Then, assign an image URL to the src attribute of the image element. Alternatively, you can set a src attribute to the image tag using the square brackets syntax like this:
img["src"] = "https://picsum.photos/200/301";
Set Multiple Src Attributes in JavaScript
// image 1 .
// image 2 .
// image 2
Using ID or class attribute, you can easily target each image element separately to set a different value to the src attribute which I will cover later in this chapter. Let me show you what 🛑 NOT to do when having multiple static image tags in your HTML page.
const img = document.querySelector("img");
In the previous example, I used the querySelector() method to target the image element which works fine for a single image element. To get a reference to all three image elements, we’ll need to use querySelectorAll().
const img = document.querySelectorAll("img");
img[0].src = "https://picsum.photos/200/301"; // image 1 img[1].src = "https://picsum.photos/200/302"; // image 2 img[2].src = "https://picsum.photos/200/303"; // image 3
This works fine, but there is a one problem with this approach. Let’s say you no longer need the first image element and remove it from the HTML code. Guess what? The second and third image elements will end up having the first and second images.
Create Image Element in JavaScript
Create an image element using the createElement() method on the document object. Then, set an image URL to its src attribute.
const img = document.createElement("img"); img.src = "https://picsum.photos/200/301"; document.body.appendChild(img);
Finally, add the image element to the DOM hierarchy by appending it to the body element. Alternatively, you can use the Image() constructor which creates a new HTMLImageElement instance and it’s functionally is equivalent to document.createElement(“img”). Optionally, you can pass width and height parameters to it.
const img = new Image(100, 200); // width, height img.src = "https://picsum.photos/200/301"; document.body.appendChild(img);
width="100" height="200" src="https://picsum.photos/200/301">
Add Inline Style to the Image in JavaScript
Using the style property, we can apply style to the image element directly in JavaScript. As you can see in the example below, I’ve applied a border as well as border radius styles to it.
let img = document.createElement("img"); img.src = "https://picsum.photos/200/301"; img.style.border = "10px solid orange"; img.style.borderRadius = "10px"; document.body.appendChild(img);
Add ID Attribute to the Image in JavaScript
Adding multiple styles to the image element individually would be tedious. Instead, let’s create a new CSS rule inside the style tags or an external CSS file with an ID selector like below.
#img-rounded-border border:10px solid red; border-radius:10px; >
As you know, it’s pretty straight forward as the value of the ID attribute should not be duplicated in a single page.
Alternatively, you can invoke the setAttribute() method on the img object with two arguments: the attribute name and the value.
img.setAttribute("id", "img-rounded-border");
Add Class Attribute to the Image in JavaScript
Unlike ID attribute, you can add multiple class names in a single image element or the same class name in multiple image elements or combinations of both. Let’s say we have a CSS rule with a class name called .img-rounded-border.
.img-rounded-border border:10px solid red; border-radius:10px; >
Then, we can add this class to the image element using the add() method on the classList property passing the class name as an argument. Continue Reading.
HTMLImageElement: Image() constructor
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement(‘img’) .
Note: This function should not be confused with the CSS image() function.
Syntax
new Image() new Image(width) new Image(width, height)
Parameters
The width of the image (i.e., the value for the width attribute).
The height of the image (i.e., the value for the height attribute).
Usage note
The entire bitmap is loaded regardless of the sizes specified in the constructor. The size specified in the constructor is reflected through the properties HTMLImageElement.width and HTMLImageElement.height of the resulting instance. The intrinsic width and height of the image in CSS pixels are reflected through the properties HTMLImageElement.naturalWidth and HTMLImageElement.naturalHeight . If no size is specified in the constructor both pairs of properties have the same values.
Examples
const myImage = new Image(100, 200); myImage.src = "picture.jpg"; document.body.appendChild(myImage);
This would be the equivalent of defining the following HTML tag inside the :
img width="100" height="200" src="picture.jpg" />
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Javascript image class api
Class representing an image. This class allows to manipulate easily images directly in the browser or in node.
This library is designed to deal with scientific images (8 or 16 bit depth) and will be able to open and process jpeg, png and uncompressed tiff images. It is designed to work in the browser as on the server side in node.
An image is characterized by:
- width and height
- colorModel (RGB, HSL, CMYK, GREY, . )
- components: number of components, Grey scale images will have 1 component while RGB will have 3 and CMYK 4.
- alpha: 0 or 1 depending if there is an alpha channel. The alpha channel define the opacity of each pixel
- channels: number of channels (components + alpha)
- bitDepth : number of bits to define the intensity of a point. The values may be 1 for a binary image (mask), 8 for a normal image (each channel contains values between 0 and 255) and 16 for scientific images (each channel contains values between 0 and 65535). The png library and tiff library included in image-js allow to deal correctly with 8 and 16 bit depth images.
- position : an array of 2 elements that allows to define a relative position to a parent image. This will be used in a crop or in the management of Region Of Interests (Roi) for example
- data : an array that contains all the points of the image. Depending the bitDepth Uint8Array (1 bit), Uint8Array (8 bits), Uint16Array (16 bits), Float32Array (32 bits)
In an image there are pixels and points:
and that contains all the values that define a particular pixel of the image.
of a specific pixel of the image
// JavaScript code using Node.js to get some info about the image. // We load the library that was installed using 'npm install image-js' const < Image >= require('image-js'); // Loading an image is asynchronous and will return a Promise. Image.load('cat.jpg').then(function (image) < console.log('Width', image.width); console.log('Height', image.height); console.log('colorModel', image.colorModel); console.log('components', image.components); console.log('alpha', image.alpha); console.log('channels', image.channels); console.log('bitDepth', image.bitDepth); >);
// Convert an image to greyscale const < Image >= require('image-js'); Image.load('cat.jpg').then(function (image) < var grey = image.grey(); grey.save('cat-grey.jpg'); >);
// Split an RGB image in its components const < Image >= require('image-js'); Image.load('cat.jpg').then(function (image) < var components = image.split(); components[0].save('cat-red.jpg'); components[1].save('cat-green.jpg'); components[2].save('cat-blur.jpg'); >);
// For this example you will need the picture of an ecstasy pill that is available on // wget https://raw.githubusercontent.com/image-js/core/854e70f50d63cc73d2dde1d2020fe61ba1b5ec05/test/img/xtc.png // the goal is to isolate the picture and to get a RGB histogram of the pill. // Practically this allows to classify pills based on the histogram similarity // This work was published at: http://dx.doi.org/10.1016/j.forsciint.2012.10.004 const < Image >= require('image-js'); const image = await Image.load('xtc.png'); const grey = image.grey(< algorithm:'lightness' >); // we create a mask, which is basically a binary image // a mask has as source a grey image and we will decide how to determine // the threshold to define what is white and what is black var mask = grey.mask(< algorithm: 'li' >); // it is possible to create an array of Region Of Interest (Roi) using // the RoiManager. A RoiManager will be applied on the original image // in order to be able to extract from the original image the regions // the result of this console.log result can directly be pasted // in the browser // console.log(mask.toDataURL()); var manager = image.getRoiManager(); manager.fromMask(mask); var rois = manager.getRoi(< positive: true, negative: false, minSurface: 100 >); // console.log(rois); // we can sort teh rois by surface // for demonstration we use an arrow function rois.sort((a, b) => b.surface - a.surface); // the first Roi (the biggest is expected to be the pill) var pillMask = rois[0].getMask(< scale: 0.7 // we will scale down the mask to take just the center of the pill and avoid border effects >); // image-js remembers the parent of the image and the relative // position of a derived image. This is the case for a crop as // well as for Roi var pill = image.extract(pillMask); pill.save('pill.jpg'); var histogram = pill.getHistograms(< maxSlots: 16 >); console.log(histogram);
// Example of use of IJS in the browser
// Image from matrix of values const [min, max] = d3.extent(temperatures) const colorScaler = d3.scaleSequential([min, max], d3.interpolateRdYlBu); // size = rows * columns * channels const data = new Uint8Array(2*3*3); for (let i = 0; i < temperatures.length; i++) < const = d3.rgb(colorScaler(temperatures[i])); data[i*3] = r; data[i*3 + 1] = g; data[i*3 + 2] = b; > const image = new Image(2, 3, data, < kind: 'RGB' >); // or const image = new Image(< width: 2, height: 3, data, kind: 'RGB'>);
HTML DOM Image Object
You can access an element by using getElementById():
Example
Tip: You can also access an element by using the images collection.
Create an Image Object
You can create an element by using the document.createElement() method:
Example
Image Object Properties
Property | Description |
---|---|
align | Not supported in HTML5. Use style.cssFloat instead. Sets or returns the value of the align attribute of an image |
alt | Sets or returns the value of the alt attribute of an image |
border | Not supported in HTML5. Use style.border instead. Sets or returns the value of the border attribute of an image |
complete | Returns whether or not the browser is finished loading an image |
crossOrigin | Sets or returns the CORS settings of an image |
height | Sets or returns the value of the height attribute of an image |
hspace | Not supported in HTML5. Use style.margin instead. Sets or returns the value of the hspace attribute of an image |
isMap | Sets or returns whether an image should be part of a server-side image-map, or not |
longDesc | Not supported in HTML5. Sets or returns the value of the longdesc attribute of an image |
lowsrc | Not supported in HTML5. Sets or returns a URL to a low-resolution version of an image |
name | Not supported in HTML5. Use id instead. Sets or returns the value of the name attribute of an image |
naturalHeight | Returns the original height of an image |
naturalWidth | Returns the original width of an image |
src | Sets or returns the value of the src attribute of an image |
useMap | Sets or returns the value of the usemap attribute of an image |
vspace | Not supported in HTML5. Use style.margin instead. Sets or returns the value of the vspace attribute of an image |
width | Sets or returns the value of the width attribute of an image |
Standard Properties and Events
The Image object also supports the standard properties and events.