Test Javascript

How to add an image in a HTML page using javascript ?

Examples of how to add an image in a HTML page using javascript:

Add an image using javascript

Let’s create a variable image with createElement («img»):

var img = document.createElement("img"); 

then indicate the name of the image (Note: if the image is not in the same directory as the html document, we can also specify the full path to the image for example ‘./path_to_img/matplotlib-grid- 02.png ‘):

img.src = "matplotlib-grid-02.png"; 

and finally display the image in the html page

var block = document.getElementById("x"); block.appendChild(img); 
         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; var div = document.getElementById("x"); div.appendChild(img); //block.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

Change the style of the div element

You can then for example modify the style of the div containing the image with

         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; var div = document.getElementById("x"); div.appendChild(img); div.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

Update the style of the image

You can also change the style of the image with

         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; img.setAttribute("style", "margin-top: 80px;"); var div = document.getElementById("x"); div.appendChild(img); div.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

References

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

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

alt text

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.

Источник

Объект Image в JavaScript

Объект Image в JavaScript

Для работы с изображениями в JavaScript используется объект Image. Данный объект является очередным свойством объекта Document. И о том, как управлять изображениями через JavaScript, Вы узнаете из этой статьи.

Конструктор у объекта Image практически не используется (да и он классический). Методы у него присутсвуют (наследуются от объекта Object), но ничего интересного из себя не представляют. Поэтому в этой статье мы разберём самое важное в объекте Image - его свойства.

Прежде чем начать обрабатывать изображение необходимо его создать. Разумеется, создание происходит в HTML, поэтому знакомый Вам тег:

Теперь мы можем обратиться к этому объекту через JavaScript:

Как видите, обращение к объекту Image очень простое: сначала пишится объект Document, а затем его свойство с именем объекта Image (это имя мы задали в атрибуте "name"). В результате выполнения этого скрипта Вы увидите: "[object HTMLImageElement]". Это сработал метод toString(), но, впрочем, забудьте, что я сейчас написал - это тема будущих статей.

ВНИМАНИЕ: Необходимо соблюдать очень важное правило: нельзя обращаться к тому, чего ещё не существует. Какой вывод из этого можно сделать? Очень простой: пока не создано изображение, его нельзя обрабатывать. То есть Вы не можете запустить приведённый здесь скрипт ДО того, как появилось изображение. На это очень часто напарываются новички, поэтому не забывайте, что прежде чем работать с чем-либо, необходимо для начала это создать.

Теперь переходим к свойствам. Начнём со свойства border. Данное свойство отвечает за размер рамки вокруг изображения. Разумеется, мы его можем и прочитать, и записать. Давайте изменим размер рамки нашего изображения:

Разумеется, есть два свойства, отвечающие за ширину и высоту изображения. Это свойства width и height объекта JavaScript. Давайте их выведем:

document.write("Ширина изображения - " + document.img.width + "
");
document.write("Высота изображения - " + document.img.height);

И последнее свойство, которое мы рассмотрим - это src. Данное свойство отвечает за путь к картинке. И давайте с Вами решим такую задачу: есть картинка и есть кнопка. При нажатии на кнопку картинка меняется.

Теперь поясню, как работает данный скрипт. Сначала мы описываем саму функцию. Создаётся переменная flag. Это некий флаг, который переключается при смене изображения. Дальше идёт функция changeImage(), которая и занимается сменой изображения. Изображению присваивается тот путь к картинке, которому соответствует флаг. После смены изображения меняется и значение флага (чтобы в следующий раз было другое изображение). За пределами скрипта создаётся форма с одной кнопкой. Здесь обратите внимание на атрибут "onClick". Этот атрибут отвечает за обработку события "Клик мыши по кнопке". О событиях мы поговорим отдельно, но здесь достаточно понять принцип. В значении атрибута "onClick" стоит функция, которую надо выполнить при нажатии на кнопку. Таким образом, у нас и меняется изображение. Надеюсь, что понятно объяснил.

Остальные свойства объекта Image в JavaScript используется достаточно редко, поэтому я их опустил. А самое важное я Вам поведал. В следующей статье мы перейдём к следующему свойству объекта Document - объект Link.

Создано 20.10.2010 19:31:48

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 31 ):

    У меня не получается, у меня вместо картинки в таблицах двух, типо инпута такое "Рисунок" в двух. Можете помочь чем-нибудь?

    Источник

    Change HTML image src using JavaScript code

    You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

    After you have the element, you can assign a new string value to its src property as follows:

    When you have the image in another folder, than you need to add the image path to the src attribute as well. The code below shows how to change the src attribute to an image inside the assets/ folder:
    Finally, if you need to run some JavaScript code after a new image has been loaded to the element, you can add an onload event loader to your img element before changing the src attribute as follows:
    Using the above code, an alert will be triggered when the new image from the src attribute has been loaded to the HTML page.

    Learn JavaScript for Beginners 🔥

    Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

    A practical and fun way to learn JavaScript and build an application using Node.js.

    About

    Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
    Learn statistics, JavaScript and other programming languages using clear examples written for people.

    Type the keyword below and hit enter

    Tags

    Click to see all tutorials tagged with:

    Источник

    Читайте также:  Python try with statement
    Оцените статью