banner



How To Draw An Image Onto A Canvas From Your Files Javascrfipt

Using images

  • « Previous
  • Next »

Until now nosotros take created our own shapes and practical styles to them. Ane of the more exciting features of <canvass> is the ability to utilise images. These can be used to practice dynamic photo compositing or as backdrops of graphs, for sprites in games, so forth. External images can be used in whatsoever format supported past the browser, such as PNG, GIF, or JPEG. You tin even use the image produced by other canvas elements on the same page every bit the source!

Importing images into a sheet is basically a ii footstep process:

  1. Get a reference to an HTMLImageElement object or to another canvas chemical element equally a source. It is also possible to utilize images past providing a URL.
  2. Depict the image on the sail using the drawImage() function.

Allow's take a look at how to do this.

Getting images to draw

The sail API is able to utilise any of the post-obit information types every bit an image source:

HTMLImageElement

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

SVGImageElement

These are images embedded using the <image> element.

HTMLVideoElement

Using an HTML <video> chemical element every bit your image source grabs the current frame from the video and uses information technology as an image.

HTMLCanvasElement

Yous can use another <canvas> element equally your image source.

These sources are collectively referred to by the type CanvasImageSource.

There are several means to become images for employ on a sheet.

Using images from the same folio

Using images from other domains

Using the crossorigin attribute of an <img> element (reflected past the HTMLImageElement.crossOrigin holding), you can request permission to load an image from some other domain for utilise in your call to drawImage(). If the hosting domain permits cross-domain admission to the image, the image can be used in your canvass without tainting it; otherwise using the paradigm will taint the canvas.

Using other canvas elements

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

One of the more than applied uses of this would be to use a 2d canvas element every bit a thumbnail view of the other larger canvas.

Creating an prototype from scratch

Some other option is to create new HTMLImageElement objects in our script. To practice this, yous can use the convenient Image() constructor:

                                  var                  img                  =                  new                  Epitome                  (                  )                  ;                  // Create new img chemical element                  img.src                  =                  'myImage.png'                  ;                  // Gear up source path                              

When this script gets executed, the image starts loading.

If yous attempt to phone call drawImage() earlier the epitome has finished loading, it won't do annihilation (or, in older browsers, may fifty-fifty throw an exception). And so you need to be sure to utilise the load consequence and then you don't try this earlier the epitome has loaded:

                                  var                  img                  =                  new                  Image                  (                  )                  ;                  // Create new img element                  img.                  addEventListener                  (                  'load'                  ,                  role                  (                  )                  {                  // execute drawImage statements hither                  }                  ,                  false                  )                  ;                  img.src                  =                  'myImage.png'                  ;                  // Fix source path                              

If you're but using i external image this can be a good approach, but once yous need to track more than one we need to resort to something more clever. It'south beyond the telescopic of this tutorial to await at paradigm pre-loading tactics, simply y'all should continue that in mind.

Embedding an epitome via data: URL

Some other possible style to include images is via the data: url. Data URLs allow you to completely define an prototype as a Base64 encoded string of characters straight in your code.

                                  var                  img                  =                  new                  Image                  (                  )                  ;                  // Create new img element                  img.src                  =                  'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=='                  ;                              

One advantage of data URLs is that the resulting paradigm is available immediately without another circular trip to the server. Another potential reward is that information technology is besides 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 epitome is non cached, and for larger images the encoded url can go quite long.

Using frames from a video

Yous can also use frames from a video being presented by a <video> element (even if the video is non visible). For case, if yous have a <video> element with the ID "myvideo", you can do this:

                                  function                  getMyVideo                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (sail.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  '2d'                  )                  ;                  return                  document.                  getElementById                  (                  'myvideo'                  )                  ;                  }                  }                              

This returns the HTMLVideoElement object for the video, which, as covered earlier, is ane of the objects that can be used as a CanvasImageSource.

Drawing images

Once we have a reference to our source image object we tin apply the drawImage() method to render information technology to the canvass. As we volition see after the drawImage() method is overloaded and has several variants. In its nearly basic form it looks like this:

drawImage(image, x, y)

Draws the CanvasImageSource specified past the image parameter at the coordinates (ten, y).

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

Case: A simple line graph

In the following case, we will use an external paradigm as the backdrop for a small line graph. Using backdrops can make your script considerably smaller considering nosotros can avoid the need for code to generate the background. In this case, we're only using ane image, so I use the image object'due south load consequence 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.

                                  office                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  var                  img                  =                  new                  Prototype                  (                  )                  ;                  img.                  onload                  =                  function                  (                  )                  {                  ctx.                  drawImage                  (img,                  0                  ,                  0                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  thirty                  ,                  96                  )                  ;                  ctx.                  lineTo                  (                  seventy                  ,                  66                  )                  ;                  ctx.                  lineTo                  (                  103                  ,                  76                  )                  ;                  ctx.                  lineTo                  (                  170                  ,                  15                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  ;                  img.src                  =                  'properties.png'                  ;                  }                              

The resulting graph looks like this:

Scaling

The 2d variant of the drawImage() method adds ii new parameters and lets u.s.a. place scaled images on the canvas.

drawImage(image, ten, y, width, height)

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

Example: Tiling an image

In this case, we'll use an image as a wallpaper and repeat information technology several times on the canvas. This is washed past looping and placing the scaled images at different positions. In the code beneath, the kickoff for loop iterates over the rows. The second for loop iterates over the columns. The image is scaled to one tertiary of its original size, which is 50x38 pixels.

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

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  certificate.                  getElementById                  (                  'canvass'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  var                  img                  =                  new                  Paradigm                  (                  )                  ;                  img.                  onload                  =                  function                  (                  )                  {                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  four                  ;                  i++                  )                  {                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  3                  ;                  j++                  )                  {                  ctx.                  drawImage                  (img,                  j                  *                  50                  ,                  i                  *                  38                  ,                  50                  ,                  38                  )                  ;                  }                  }                  }                  ;                  img.src                  =                  'rhino.jpg'                  ;                  }                              

The resulting canvas looks like this:

Slicing

The tertiary and last variant of the drawImage() method has viii parameters in addition to the image source. Information technology lets usa cutting out a section of the source image, and so scale and draw it on our canvas.

drawImage(prototype, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

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

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

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

Slicing tin can be a useful tool when you want to make compositions. You could have all elements in a single prototype file and utilize this method to composite a complete cartoon. For example, if you desire to make a nautical chart you could take a PNG paradigm containing all the necessary text in a unmarried file and depending on your data could change the calibration of your nautical chart fairly easily. Another advantage is that you don't demand to load every image individually, which can improve load performance.

Example: Framing an prototype

In this example, nosotros'll use the aforementioned rhino as in the previous instance, just nosotros'll piece out its head and composite it into a moving-picture show frame. The picture show frame prototype is a 24-bit PNG which includes a drop shadow. Because 24-fleck PNG images include a full 8-bit alpha aqueduct, unlike GIF and 8-bit PNG images, information technology can be placed onto any background without worrying about a matte color.

                                                                            <html                    >                                                                              <body                                          onload                                              =                        "                                                  draw                          (                          )                          ;                                                "                                                              >                                                                              <canvas                    id                                          =                      "canvas"                                        width                                          =                      "150"                                        height                                          =                      "150"                                        >                                                                              </canvas                    >                                                                              <div                                          style                                              =                        "                                                  brandish                          :none;                                                "                                                              >                                                                              <img                    id                                          =                      "source"                                        src                                          =                      "rhino.jpg"                                        width                                          =                      "300"                                        meridian                                          =                      "227"                                        >                                                                              <img                    id                                          =                      "frame"                                        src                                          =                      "canvas_picture_frame.png"                                        width                                          =                      "132"                                        meridian                                          =                      "150"                                        >                                                                              </div                    >                                                                              </body                    >                                                                              </html                    >                                                
                                  function                  describe                  (                  )                  {                  var                  canvas                  =                  certificate.                  getElementById                  (                  'sheet'                  )                  ;                  var                  ctx                  =                  canvas.                  getContext                  (                  '2d'                  )                  ;                  // Draw slice                  ctx.                  drawImage                  (certificate.                  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 <img> tags straight in our HTML source and retrieved the images from those. The images are hidden from output by setting the CSS belongings display to none for those images.

The script itself is very simple. Each <img> is assigned an ID aspect, which makes them easy to select using certificate.getElementById(). We then use drawImage() to slice the rhino out of the beginning epitome and calibration him onto the sail, then draw the frame on meridian using a 2d drawImage() telephone call.

In the final example of this affiliate, nosotros'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 prototype and a frame is fatigued around it.

In this case, every image has a fixed width and height, as does the frame that's drawn around them. You lot could enhance the script and then that it uses the image'south width and height to brand the frame fit perfectly around it.

The lawmaking beneath should exist self-explanatory. We loop through the document.images container and add new canvas elements appropriately. Probably the only thing to annotation, for those non and then familiar with the DOM, is the use of the Node.insertBefore method. insertBefore() is a method of the parent node (a table jail cell) of the element (the paradigm) before which we desire to insert our new node (the canvas element).

                                                                            <html                    >                                                                              <body                                          onload                                              =                        "                                                  depict                          (                          )                          ;                                                "                                                              >                                                                              <tabular array                    >                                                                              <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 hither'due south some CSS to brand things look nice:

                                  trunk                  {                  background                  :                  0 -100px repeat-ten                                      url                    (bg_gallery.png)                                    #4F191A;                  margin                  :                  10px;                  }                  img                  {                  display                  :                  none;                  }                  tabular array                  {                  margin                  :                  0 auto;                  }                  td                  {                  padding                  :                  15px;                  }                              

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

                                  function                  describe                  (                  )                  {                  // Loop through all images                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  document.images.length;                  i++                  )                  {                  // Don't add a canvas for the frame image                  if                  (certificate.images[i]                  .                  getAttribute                  (                  'id'                  )                  !=                  'frame'                  )                  {                  // Create canvas chemical element                  canvas                  =                  document.                  createElement                  (                  'sail'                  )                  ;                  canvas.                  setAttribute                  (                  'width'                  ,                  132                  )                  ;                  canvas.                  setAttribute                  (                  'tiptop'                  ,                  150                  )                  ;                  // Insert before the prototype                  document.images[i]                  .parentNode.                  insertBefore                  (sail,certificate.images[i]                  )                  ;                  ctx                  =                  sheet.                  getContext                  (                  '2d'                  )                  ;                  // Depict image to canvas                  ctx.                  drawImage                  (document.images[i]                  ,                  xv                  ,                  20                  )                  ;                  // Add together 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 cartoon context's imageSmoothingEnabled property to control the use of image smoothing algorithms when scaling images within your context. By default, this is truthful, meaning images volition be smoothed when scaled. Y'all tin disable this characteristic similar this:

                ctx.mozImageSmoothingEnabled                  =                  imitation                  ;                  ctx.webkitImageSmoothingEnabled                  =                  false                  ;                  ctx.msImageSmoothingEnabled                  =                  fake                  ;                  ctx.imageSmoothingEnabled                  =                  false                  ;                              
  • « Previous
  • Next »

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

Posted by: hammerstherong1944.blogspot.com

0 Response to "How To Draw An Image Onto A Canvas From Your Files Javascrfipt"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel