How do i put an image in javascript?

  • « Previous
  • Next »

Until now we have created our own shapes and applied styles to them. One of the more exciting features of 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:

HTMLImageElement

These are images created using the Image() constructor, as well as any

How do i put an image in javascript?

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.

<html lang="en">
  <body onload="draw();">
    <canvas id="canvas" width="150" height="150">canvas>
    <div style="display:none;">
      <img id="source" src="rhino.jpg" width="300" height="227" />
      <img id="frame" src="canvas_picture_frame.png" width="132" height="150" />
    div>
  body>
html>

function draw() {
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');

  // Draw slice
  ctx.drawImage(document.getElementById('source'),
                33, 71, 104, 124, 21, 20, 87, 104);

  // Draw frame
  ctx.drawImage(document.getElementById('frame'), 0, 0);
}

We took a different approach to loading the images this time. Instead of loading them by creating new HTMLImageElement objects, we included them as 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.

The script itself is very simple. Each 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.

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

<html lang="en">
  <body onload="draw();">
    <table>
      <tr>
        <td><img src="gallery_1.jpg" />td>
        <td><img src="gallery_2.jpg" />td>
        <td><img src="gallery_3.jpg" />td>
        <td><img src="gallery_4.jpg" />td>
      tr>
      <tr>
        <td><img src="gallery_5.jpg" />td>
        <td><img src="gallery_6.jpg" />td>
        <td><img src="gallery_7.jpg" />td>
        <td><img src="gallery_8.jpg" />td>
      tr>
    table>
    <img id="frame" src="canvas_picture_frame.png" width="132" height="150" />
  body>
html>

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

body {
  background: 0 -100px repeat-x url(bg_gallery.png) #4f191a;
  margin: 10px;
}

img {
  display: none;
}

table {
  margin: 0 auto;
}

td {
  padding: 15px;
}

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

function draw() {
  // Loop through all images
  for (const image of document.images) {
    // Don't add a canvas for the frame image
    if (image.getAttribute('id') !== 'frame') {


      // Create canvas element
      const canvas = document.createElement("canvas");
      canvas.setAttribute("width", 132);
      canvas.setAttribute("height", 150);

      // Insert before the image
      image.parentNode.insertBefore(canvas, image);

      ctx = canvas.getContext("2d");

      // Draw image to canvas
      ctx.drawImage(image, 15, 20);

      // Add frame
      ctx.drawImage(document.getElementById("frame"), 0, 0);
    }
  }
}

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. You can disable this feature like this:

ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

  • « Previous
  • Next »

How do you import an image into JavaScript?

JavaScript Anywhere.
Open the screen of images. Tap the image button on the toolbar (on the bottom left of the project screen)..
Import images. Tap the plus button on the navigation bar (on the top right of the images screen). ... .
Copy an image tag. ... .
Paste the image tag to HTML..

How do you declare an image in JavaScript?

Create an empty img element using document. createElement() method. Then set its attributes like (src, height, width, alt, title etc). Finally, insert it into the document.

How do you insert an image in coding?

The HTML tag is used to embed an image in a web page. Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced image. The tag is empty, it contains attributes only, and does not have a closing tag.

How do I put an image on HTML?

How to Insert an Image in HTML. To insert an image in HTML, use the image tag and include a source and alt attribute. Like any other HTML element, you'll add images to the body section of your HTML file. The HTML image element is an “empty element,” meaning it does not have a closing tag.