Как вставить картинку в javascript
Перейти к содержимому

Как вставить картинку в javascript

  • автор:

Using images

Until now we have created our own shapes and applied styles to them. One of the more exciting features of <canvas> is the ability to use images. These can be used to do dynamic photo compositing or as backdrops of graphs, for sprites in games, and so forth. External images can be used in any format supported by the browser, such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source!

Importing images into a canvas is basically a two step process:

  1. Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL.
  2. Draw the image on the canvas using the drawImage() function.

Let’s take a look at how to do this.

Getting images to draw

The canvas API is able to use any of the following data types as an image source:

These are images created using the Image() constructor, as well as any <img> element.

These are images embedded using the <image> element.

Using an HTML <video> element as your image source grabs the current frame from the video and uses it as an image.

You can use another <canvas> element as your image source.

A bitmap image, eventually cropped. Such type are used to extract part of an image, a sprite, from a larger image

A special kind of <canvas> that is not displayed and is prepared without being displayed. Using such an image source allows to switch to it without the composition of the content to be visible to the user.

An image representing one single frame of a video.

There are several ways to get images for use on a canvas.

Using images from the same page

We can obtain a reference to images on the same page as the canvas by using one of:

  • The document.images collection
  • The document.getElementsByTagName() method
  • If you know the ID of the specific image you wish to use, you can use document.getElementById() to retrieve that specific image

Using images from other domains

Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), you can request permission to load an image from another domain for use in your call to drawImage() . If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will taint the canvas.

Using other canvas elements

Just as with normal images, we access other canvas elements using either the document.getElementsByTagName() or document.getElementById() method. Be sure you’ve drawn something to the source canvas before using it in your target canvas.

One of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas.

Creating an image from scratch

Another option is to create new HTMLImageElement objects in our script. To do this, you can use the convenient Image() constructor:

When this script gets executed, the image starts loading.

If you try to call drawImage() before the image has finished loading, it won’t do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don’t try this before the image has loaded:

If you’re only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. It’s beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind.

Embedding an image via data: URL

Another possible way to include images is via the data: URL. Data URLs allow you to completely define an image as a Base64 encoded string of characters directly in your code.

One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential advantage is that it is also possible to encapsulate in one file all of your CSS, JavaScript, HTML, and images, making it more portable to other locations.

Some disadvantages of this method are that your image is not cached, and for larger images the encoded URL can become quite long.

Using frames from a video

You can also use frames from a video being presented by a <video> element (even if the video is not visible). For example, if you have a <video> element with the ID «myvideo», you can do this:

This returns the HTMLVideoElement object for the video, which, as covered earlier, can be used as an image source for the canvas.

Drawing images

Once we have a reference to our source image object we can use the drawImage() method to render it to the canvas. As we will see later the drawImage() method is overloaded and has several variants. In its most basic form it looks like this:

Draws the image specified by the image parameter at the coordinates ( x , y ).

Note: SVG images must specify a width and height in the root <svg> element.

Example: A simple line graph

In the following example, we will use an external image as the backdrop for a small line graph. Using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. In this example, we’re only using one image, so I use the image object’s load event handler to execute the drawing statements. The drawImage() method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas.

The resulting graph looks like this:

Screenshot Live sample

Scaling

The second variant of the drawImage() method adds two new parameters and lets us place scaled images on the canvas.

This adds the width and height parameters, which indicate the size to which to scale the image when drawing it onto the canvas.

Example: Tiling an image

In this example, we’ll use an image as a wallpaper and repeat it several times on the canvas. This is done by looping and placing the scaled images at different positions. In the code below, the first for loop iterates over the rows. The second for loop iterates over the columns. The image is scaled to one third of its original size, which is 50×38 pixels.

Note: Images can become blurry when scaling up or grainy if they’re scaled down too much. Scaling is probably best not done if you’ve got some text in it which needs to remain legible.

The resulting canvas looks like this:

Screenshot Live sample

Slicing

The third and last variant of the drawImage() method has eight parameters in addition to the image source. It lets us cut out a section of the source image, then scale and draw it on our canvas.

Given an image , this function takes the area of the source image specified by the rectangle whose top-left corner is ( sx , sy ) and whose width and height are sWidth and sHeight and draws it into the canvas, placing it on the canvas at ( dx , dy ) and scaling it to the size specified by dWidth and dHeight .

To really understand what this does, it may help to look at this image:

The rectangular source image top left coordinates are sx and sy with a width and height of sWidth and sHeight respectively. The source image is translated to the destination canvas where the top-left corner coordinates are dx and dy, maintaining its aspect ratio, with a width and height of dWidth and dHeight respectively.

The first four parameters define the location and size of the slice on the source image. The last four parameters define the rectangle into which to draw the image on the destination canvas.

Slicing can be a useful tool when you want to make compositions. You could have all elements in a single image file and use this method to composite a complete drawing. For instance, if you want to make a chart you could have a PNG image containing all the necessary text in a single file and depending on your data could change the scale of your chart fairly easily. Another advantage is that you don’t need to load every image individually, which can improve load performance.

Example: Framing an image

In this example, we’ll use the same rhino as in the previous example, but we’ll slice out its head and composite it into a picture frame. The picture frame image is a 24-bit PNG which includes a drop shadow. Because 24-bit PNG images include a full 8-bit alpha channel, unlike GIF and 8-bit PNG images, it can be placed onto any background without worrying about a matte color.

We took a different approach to loading the images this time. Instead of loading them by creating new HTMLImageElement objects, we included them as <img> tags directly in our HTML source and retrieved the images from those. The images are hidden from output by setting the CSS property display to none for those images.

Screenshot Live sample

The script itself is very simple. Each <img> is assigned an ID attribute, which makes them easy to select using document.getElementById() . We then use drawImage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second drawImage() call.

Art gallery example

In the final example of this chapter, we’ll build a little art gallery. The gallery consists of a table containing several images. When the page is loaded, a <canvas> element is inserted for each image and a frame is drawn around it.

In this case, every image has a fixed width and height, as does the frame that’s drawn around them. You could enhance the script so that it uses the image’s width and height to make the frame fit perfectly around it.

The code below should be self-explanatory. We loop through the document.images container and add new canvas elements accordingly. Probably the only thing to note, for those not so familiar with the DOM, is the use of the Node.insertBefore method. insertBefore() is a method of the parent node (a table cell) of the element (the image) before which we want to insert our new node (the canvas element).

And here’s some CSS to make things look nice:

Tying it all together is the JavaScript to draw our framed images:

Controlling image scaling behavior

As mentioned previously, scaling images can result in fuzzy or blocky artifacts due to the scaling process. You can use the drawing context’s imageSmoothingEnabled property to control the use of image smoothing algorithms when scaling images within your context. By default, this is true , meaning images will be smoothed when scaled.

как вставить картинку в js

Аватар пользователя Aleksey

Для создания изображения можем создать элемент <img> с помощью метода createElement . Далее, чтобы добавить изображение на веб-страницу, нужно установить соответствующие свойства этому элементу.

Определим, где должно расоплагаться изображение (родительский контейнер).

Теперь напишем js код:

Этот код создаст элемент <img> , устанавливает ему путь и альтернативный текст, а затем добавляет его в контейнер, который имеет идентификатор image-container .

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

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

Table of contents

Add an image using javascript

Let's create a variable image with 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 '):

and finally display the image in the html page

Sample code using this image

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

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

Example of code

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

References

Author profile-image

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.

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

Create a static image tag with a src attribute with an image URL in the HTML file.

Exit fullscreen mode

output:

alt text

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.

Pretty straight forward right?

Let’s see how to set a src attribute dynamically via JavaScript next.

Set Src Attribute in JavaScript

In the HTML file, create an HTML image tag like so:

Exit fullscreen mode

In JavaScript, get a reference to the image tag using the querySelector() method.

Exit fullscreen mode

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:

Exit fullscreen mode

output:

alt text

Set Multiple Src Attributes in JavaScript

Let’s say you have three image elements in the HTML page in different parts.

Exit fullscreen mode

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.

Exit fullscreen mode

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().

Exit fullscreen mode

This will get all of the image element references and create a Node List Array from them.

Exit fullscreen mode

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.

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.

Exit fullscreen mode

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.

Exit fullscreen mode

It will be equivalent to this in HTML:

Exit fullscreen mode

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.

Exit fullscreen mode

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.

Exit fullscreen mode

Then, assign it to the ID attribute of the image element using its ID property.

Exit fullscreen mode

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.

Exit fullscreen mode

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.

Exit fullscreen mode

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *