banner



How To Draw A Picture Frame

Using images

  • « Previous
  • Next »

Until at present nosotros have created our ain shapes and applied styles to them. One of the more exciting features of <canvas> is the ability to use images. These can exist 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. Y'all tin even use the image produced past other canvas elements on the aforementioned folio as the source!

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

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

Allow'southward accept a look at how to exercise this.

Getting images to draw

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

HTMLImageElement

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

SVGImageElement

These are images embedded using the <epitome> element.

HTMLVideoElement

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

HTMLCanvasElement

Y'all can use some other <canvas> element as your image source.

These sources are collectively referred to by the type CanvasImageSource.

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

Using images from the same page

Using images from other domains

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

Using other canvass elements

Just every bit with normal images, we admission other canvas elements using either the certificate.getElementsByTagName() or document.getElementById() method. Be certain you've fatigued something to the source canvas before using it in your target canvas.

One of the more than practical uses of this would be to utilise a second sheet element equally a thumbnail view of the other larger canvas.

Creating an image from scratch

Another choice is to create new HTMLImageElement objects in our script. To do this, y'all can employ the convenient Prototype() constructor:

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

When this script gets executed, the image starts loading.

If you effort to call drawImage() earlier the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). And then you need to exist certain to use the load event so you lot don't try this before the paradigm has loaded:

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

If y'all're just using one external image this can be a good approach, but once yous demand to runway more one we need to resort to something more clever. It'due south beyond the scope of this tutorial to wait at image pre-loading tactics, simply you should keep that in heed.

Embedding an paradigm via data: URL

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

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

One advantage of data URLs is that the resulting epitome is available immediately without another round trip to the server. Some other potential advantage is that it is as well 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 prototype is not cached, and for larger images the encoded url can become quite long.

Using frames from a video

You can besides use frames from a video beingness 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:

                              part                getMyVideo                (                )                {                var                canvas                =                certificate.                getElementById                (                'canvas'                )                ;                if                (canvas.getContext)                {                var                ctx                =                sail.                getContext                (                '2nd'                )                ;                return                certificate.                getElementById                (                'myvideo'                )                ;                }                }                          

This returns the HTMLVideoElement object for the video, which, every bit covered earlier, is 1 of the objects that tin exist used as a CanvasImageSource.

Drawing images

Once we have a reference to our source image object we tin utilize the drawImage() method to return it to the canvas. Equally we volition run into later the drawImage() method is overloaded and has several variants. In its most basic grade it looks like this:

drawImage(image, x, y)

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

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

Case: A unproblematic line graph

In the following example, nosotros will use an external image as the backdrop for a pocket-sized line graph. Using backdrops can make your script considerably smaller because we tin can avoid the need for lawmaking to generate the background. In this instance, nosotros're merely using one image, so I utilize the image object'southward load event handler to execute the drawing statements. The drawImage() method places the properties at the coordinate (0, 0), which is the peak-left corner of the sheet.

                              function                draw                (                )                {                var                ctx                =                document.                getElementById                (                'canvas'                )                .                getContext                (                '2d'                )                ;                var                img                =                new                Image                (                )                ;                img.                onload                =                role                (                )                {                ctx.                drawImage                (img,                0                ,                0                )                ;                ctx.                beginPath                (                )                ;                ctx.                moveTo                (                30                ,                96                )                ;                ctx.                lineTo                (                lxx                ,                66                )                ;                ctx.                lineTo                (                103                ,                76                )                ;                ctx.                lineTo                (                170                ,                fifteen                )                ;                ctx.                stroke                (                )                ;                }                ;                img.src                =                'backdrop.png'                ;                }                          

The resulting graph looks like this:

Screenshot Live sample

Scaling

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

drawImage(epitome, 10, y, width, summit)

This adds the width and peak parameters, which indicate the size to which to calibration the image when drawing it onto the sheet.

Instance: Tiling an image

In this case, we'll employ an image as a wallpaper and repeat it several times on the sheet. This is washed by looping and placing the scaled images at dissimilar 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 50x38 pixels.

Notation: Images can become blurry when scaling upward or grainy if they're scaled down too much. Scaling is probably all-time not done if you've got some text in it which needs to remain legible.

                              function                draw                (                )                {                var                ctx                =                document.                getElementById                (                'sail'                )                .                getContext                (                '2d'                )                ;                var                img                =                new                Prototype                (                )                ;                img.                onload                =                part                (                )                {                for                (                var                i                =                0                ;                i                <                4                ;                i++                )                {                for                (                var                j                =                0                ;                j                <                three                ;                j++                )                {                ctx.                drawImage                (img,                j                *                50                ,                i                *                38                ,                fifty                ,                38                )                ;                }                }                }                ;                img.src                =                'rhino.jpg'                ;                }                          

The resulting canvas looks like this:

Screenshot Live sample

Slicing

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

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

Given an prototype, 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 information technology 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 first 4 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 epitome on the destination canvas.

Slicing can be a useful tool when you want to make compositions. Y'all could have all elements in a single image file and apply this method to blended a complete cartoon. For instance, if you want to make a chart y'all could have a PNG paradigm containing all the necessary text in a single file and depending on your information could change the scale of your chart fairly hands. Some other advantage is that you don't need to load every image individually, which can improve load operation.

Example: Framing an image

In this example, nosotros'll use the same rhino as in the previous example, only we'll slice out its head and blended it into a moving picture frame. The picture frame epitome is a 24-chip PNG which includes a drop shadow. Because 24-bit PNG images include a full 8-bit alpha channel, different GIF and viii-fleck PNG images, it can be placed onto whatever background without worrying almost a matte colour.

                                                                    <html                  >                                                                      <torso                                      onload                                          =                      "                                              describe                        (                        )                        ;                                            "                                                        >                                                                      <sheet                  id                                      =                    "canvass"                                    width                                      =                    "150"                                    height                                      =                    "150"                                    >                                                                      </canvas                  >                                                                      <div                                      style                                          =                      "                                              display                        :none;                                            "                                                        >                                                                      <img                  id                                      =                    "source"                                    src                                      =                    "rhino.jpg"                                    width                                      =                    "300"                                    meridian                                      =                    "227"                                    >                                                                      <img                  id                                      =                    "frame"                                    src                                      =                    "canvas_picture_frame.png"                                    width                                      =                    "132"                                    height                                      =                    "150"                                    >                                                                      </div                  >                                                                      </body                  >                                                                      </html                  >                                          
                              role                depict                (                )                {                var                sheet                =                certificate.                getElementById                (                'canvas'                )                ;                var                ctx                =                canvas.                getContext                (                'second'                )                ;                // Draw piece                ctx.                drawImage                (document.                getElementById                (                'source'                )                ,                33                ,                71                ,                104                ,                124                ,                21                ,                20                ,                87                ,                104                )                ;                // Draw frame                ctx.                drawImage                (certificate.                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 direct 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.

Screenshot Live sample

The script itself is very simple. Each <img> is assigned an ID attribute, which makes them easy to select using certificate.getElementById(). We then employ drawImage() to slice the rhino out of the first image and scale him onto the canvas, and then depict the frame on peak using a 2d 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 folio is loaded, a <sail> element is inserted for each image and a frame is fatigued around information technology.

In this case, every paradigm has a fixed width and height, every bit does the frame that's drawn effectually them. Yous could enhance the script and then that it uses the image's width and height to make the frame fit perfectly effectually it.

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

                                                                    <html                  >                                                                      <trunk                                      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"                                    >                                                                      </torso                  >                                                                      </html                  >                                          

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

                              body                {                background                :                0 -100px repeat-10                                  url                  (bg_gallery.png)                                #4F191A;                margin                :                10px;                }                img                {                brandish                :                none;                }                table                {                margin                :                0 automobile;                }                td                {                padding                :                15px;                }                          

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

                              function                draw                (                )                {                // Loop through all images                for                (                var                i                =                0                ;                i                <                document.images.length;                i++                )                {                // Don't add a sheet for the frame image                if                (document.images[i]                .                getAttribute                (                'id'                )                !=                'frame'                )                {                // Create canvas chemical element                canvas                =                certificate.                createElement                (                'sheet'                )                ;                canvas.                setAttribute                (                'width'                ,                132                )                ;                canvas.                setAttribute                (                'summit'                ,                150                )                ;                // Insert earlier the prototype                document.images[i]                .parentNode.                insertBefore                (sail,certificate.images[i]                )                ;                ctx                =                sheet.                getContext                (                'second'                )                ;                // Depict prototype to sail                ctx.                drawImage                (document.images[i]                ,                xv                ,                xx                )                ;                // Add frame                ctx.                drawImage                (certificate.                getElementById                (                'frame'                )                ,                0                ,                0                )                ;                }                }                }                          

Controlling image scaling behavior

As mentioned previously, scaling images tin consequence in fuzzy or blocky artifacts due to the scaling process. You tin utilize the drawing context's imageSmoothingEnabled property to command the employ of paradigm smoothing algorithms when scaling images within your context. By default, this is truthful, meaning images will be smoothed when scaled. You lot can disable this characteristic like this:

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

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

Posted by: weidmanatudeas.blogspot.com

0 Response to "How To Draw A Picture Frame"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel