banner



how to draw multiple images on html canvas

Using images

  • « Previous
  • Adjacent »

Until now we take created our ain shapes and applied styles to them. One of the more than heady features of <sail> is the power to use images. These can be used to practice dynamic photo compositing or equally backdrops of graphs, for sprites in games, so along. External images tin be used in any format supported by the browser, such as PNG, GIF, or JPEG. You lot can even use the image produced past other canvas elements on the same page as the source!

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

  1. Get a reference to an HTMLImageElement object or to some other canvass chemical element as a source. It is as well possible to apply images by providing a URL.
  2. Draw the epitome on the canvas using the drawImage() function.

Allow's have a wait at how to do this.

Getting images to draw

The sheet API is able to use any of the following data types every bit an epitome source:

HTMLImageElement

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

SVGImageElement

These are images embedded using the <epitome> element.

HTMLVideoElement

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

HTMLCanvasElement

Yous can use some other <sheet> chemical element as your prototype source.

These sources are collectively referred to by the type CanvasImageSource.

At that place are several ways to get images for use on a canvas.

Using images from the aforementioned page

Using images from other domains

Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), yous can request permission to load an paradigm from some other 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 canvass without tainting information technology; otherwise using the epitome will taint the canvas.

Using other canvas elements

Only equally with normal images, we access other canvas elements using either the certificate.getElementsByTagName() or certificate.getElementById() method. Be certain you lot've drawn something to the source canvas before using it in your target canvas.

1 of the more applied uses of this would be to utilize a 2d canvas element as a thumbnail view of the other larger sheet.

Creating an paradigm from scratch

Some other choice is to create new HTMLImageElement objects in our script. To do this, yous can employ the convenient Epitome() constructor:

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

When this script gets executed, the image starts loading.

If you lot try to call drawImage() before the image has finished loading, information technology won't do annihilation (or, in older browsers, may fifty-fifty throw an exception). So yous need to exist certain to use the load event so you don't try this before the epitome has loaded:

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

If you lot're only using one external epitome this can be a good approach, but once yous demand to track more than one nosotros need to resort to something more clever. It'southward beyond the scope of this tutorial to look at image pre-loading tactics, simply you should go along that in mind.

Embedding an paradigm via data: URL

Another possible way to include images is via the data: url. Data URLs allow you to completely define an image every bit a Base64 encoded cord of characters direct in your lawmaking.

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

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

Some disadvantages of this method are that your image 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 not visible). For example, if you lot take a <video> chemical element with the ID "myvideo", you can do this:

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

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

Drawing images

In one case we have a reference to our source image object we can utilise the drawImage() method to render it to the canvas. As we volition see subsequently the drawImage() method is overloaded and has several variants. In its most bones form it looks like this:

drawImage(image, ten, y)

Draws the CanvasImageSource specified past the paradigm 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 instance, we will use an external image as the properties for a small line graph. Using backdrops can brand your script considerably smaller because we can avoid the need for code to generate the background. In this case, nosotros're only using 1 image, so I use the paradigm object's load outcome handler to execute the cartoon statements. The drawImage() method places the backdrop at the coordinate (0, 0), which is the elevation-left corner of the canvas.

                              function                draw                (                )                {                var                ctx                =                document.                getElementById                (                'canvass'                )                .                getContext                (                '2nd'                )                ;                var                img                =                new                Image                (                )                ;                img.                onload                =                office                (                )                {                ctx.                drawImage                (img,                0                ,                0                )                ;                ctx.                beginPath                (                )                ;                ctx.                moveTo                (                xxx                ,                96                )                ;                ctx.                lineTo                (                70                ,                66                )                ;                ctx.                lineTo                (                103                ,                76                )                ;                ctx.                lineTo                (                170                ,                15                )                ;                ctx.                stroke                (                )                ;                }                ;                img.src                =                'backdrop.png'                ;                }                          

The resulting graph looks similar this:

Screenshot Live sample

Scaling

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

drawImage(paradigm, 10, y, width, height)

This adds the width and height parameters, which signal the size to which to scale the image when cartoon information technology onto the canvas.

Case: Tiling an epitome

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 lawmaking below, the get-go for loop iterates over the rows. The second for loop iterates over the columns. The prototype is scaled to one third of its original size, which is 50x38 pixels.

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

                              part                draw                (                )                {                var                ctx                =                document.                getElementById                (                'canvas'                )                .                getContext                (                '2nd'                )                ;                var                img                =                new                Image                (                )                ;                img.                onload                =                role                (                )                {                for                (                var                i                =                0                ;                i                <                4                ;                i++                )                {                for                (                var                j                =                0                ;                j                <                3                ;                j++                )                {                ctx.                drawImage                (img,                j                *                fifty                ,                i                *                38                ,                50                ,                38                )                ;                }                }                }                ;                img.src                =                'rhino.jpg'                ;                }                          

The resulting canvas looks similar this:

Screenshot Live sample

Slicing

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

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

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

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

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

Slicing tin be a useful tool when you want to brand compositions. You could take all elements in a single image file and use this method to composite a complete drawing. For case, if you want to brand a chart you could take a PNG paradigm containing all the necessary text in a single file and depending on your data could modify the scale of your chart fairly easily. Another advantage is that you don't need to load every image individually, which can better load operation.

Example: Framing an image

In this case, nosotros'll utilize the same rhino as in the previous example, but we'll piece out its caput and composite information technology into a motion-picture show frame. The motion-picture show frame prototype is a 24-bit PNG which includes a drop shadow. Considering 24-bit PNG images include a full 8-chip blastoff channel, unlike GIF and 8-bit PNG images, information technology can be placed onto whatever background without worrying about a matte colour.

                                                                    <html                  >                                                                      <body                                      onload                                          =                      "                                              depict                        (                        )                        ;                                            "                                                        >                                                                      <sheet                  id                                      =                    "sheet"                                    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"                                    acme                                      =                    "150"                                    >                                                                      </div                  >                                                                      </body                  >                                                                      </html                  >                                          
                              function                draw                (                )                {                var                canvas                =                certificate.                getElementById                (                'sheet'                )                ;                var                ctx                =                canvas.                getContext                (                '2d'                )                ;                // Depict slice                ctx.                drawImage                (certificate.                getElementById                (                'source'                )                ,                33                ,                71                ,                104                ,                124                ,                21                ,                20                ,                87                ,                104                )                ;                // Draw frame                ctx.                drawImage                (certificate.                getElementById                (                'frame'                )                ,                0                ,                0                )                ;                }                          

We took a unlike approach to loading the images this time. Instead of loading them by creating new HTMLImageElement objects, nosotros 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 aspect, which makes them easy to select using document.getElementById(). Nosotros then apply drawImage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on height using a second drawImage() call.

In the terminal case 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 <sail> element is inserted for each paradigm and a frame is drawn around it.

In this case, every image has a fixed width and height, equally does the frame that'southward drawn around them. You lot could enhance the script so that it uses the image'southward width and acme to make the frame fit perfectly around it.

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

                                                                    <html                  >                                                                      <body                                      onload                                          =                      "                                              draw                        (                        )                        ;                                            "                                                        >                                                                      <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                  >                                                                      </tabular array                  >                                                                      <img                  id                                      =                    "frame"                                    src                                      =                    "canvas_picture_frame.png"                                    width                                      =                    "132"                                    tiptop                                      =                    "150"                                    >                                                                      </body                  >                                                                      </html                  >                                          

And hither'due south some CSS to brand things look nice:

                              body                {                background                :                0 -100px echo-ten                                  url                  (bg_gallery.png)                                #4F191A;                margin                :                10px;                }                img                {                display                :                none;                }                table                {                margin                :                0 car;                }                td                {                padding                :                15px;                }                          

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

                              office                draw                (                )                {                // Loop through all images                for                (                var                i                =                0                ;                i                <                document.images.length;                i++                )                {                // Don't add a canvas for the frame image                if                (document.images[i]                .                getAttribute                (                'id'                )                !=                'frame'                )                {                // Create canvas element                canvass                =                document.                createElement                (                'canvas'                )                ;                sail.                setAttribute                (                'width'                ,                132                )                ;                canvas.                setAttribute                (                'pinnacle'                ,                150                )                ;                // Insert before the image                certificate.images[i]                .parentNode.                insertBefore                (canvas,certificate.images[i]                )                ;                ctx                =                sail.                getContext                (                '2d'                )                ;                // Draw image to canvas                ctx.                drawImage                (document.images[i]                ,                fifteen                ,                20                )                ;                // Add frame                ctx.                drawImage                (certificate.                getElementById                (                'frame'                )                ,                0                ,                0                )                ;                }                }                }                          

Controlling epitome scaling behavior

As mentioned previously, scaling images tin result in fuzzy or blocky artifacts due to the scaling process. Y'all can use the drawing context'southward imageSmoothingEnabled holding to control the employ of image smoothing algorithms when scaling images within your context. By default, this is true, pregnant 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 »

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

Posted by: musgroveansenuter.blogspot.com

0 Response to "how to draw multiple images on html canvas"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel