Html5 Canvas Draw Image in Circle
Using images
- « Previous
- Next »
Until now we accept created our ain shapes and practical styles to them. One of the more exciting features of <sheet>
is the ability to use images. These can be used to exercise dynamic photo compositing or as backdrops of graphs, for sprites in games, and and so forth. External images can exist used in any format supported by the browser, such as PNG, GIF, or JPEG. You tin even employ the image produced past other sheet elements on the same page equally the source!
Importing images into a sheet is basically a ii step process:
- Become a reference to an
HTMLImageElement
object or to another canvas element as a source. Information technology is also possible to utilise images by providing a URL. - Draw the image on the canvas using the
drawImage()
function.
Let's accept a await at how to do this.
Getting images to draw
The canvas API is able to use any of the following data types every bit an epitome source:
-
HTMLImageElement
-
These are images created using the
Prototype()
constructor, as well as whatever<img>
element. -
SVGImageElement
-
These are images embedded using the
<image>
chemical element. -
HTMLVideoElement
-
Using an HTML
<video>
element as your epitome source grabs the current frame from the video and uses it every bit an image. -
HTMLCanvasElement
-
You lot can use another
<canvas>
element equally your image source.
These sources are collectively referred to by the blazon CanvasImageSource
.
There are several ways to go images for utilise on a canvas.
Using images from the aforementioned page
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 another domain for use in your call to drawImage()
. If the hosting domain permits cantankerous-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the paradigm volition taint the canvas.
Using other canvas elements
Just as with normal images, we access other canvass elements using either the certificate.getElementsByTagName()
or certificate.getElementById()
method. Be sure you've drawn something to the source canvas before using it in your target canvas.
One of the more than practical uses of this would be to use a 2d canvas chemical element as a thumbnail view of the other larger sheet.
Creating an image from scratch
Another choice is to create new HTMLImageElement
objects in our script. To do this, yous can utilise the convenient Image()
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 try to call drawImage()
before the image has finished loading, it won't practice anything (or, in older browsers, may even throw an exception). And then yous need to be sure to use the load event so you don't endeavor this earlier the image has loaded:
var img = new Image ( ) ; // Create new img chemical element img. addEventListener ( 'load' , function ( ) { // execute drawImage statements hither } , imitation ) ; img.src = 'myImage.png' ; // Set source path
If you lot're but using one external image this can be a good approach, but once you need to track more than 1 we need to resort to something more clever. It's beyond the telescopic of this tutorial to look at prototype pre-loading tactics, simply you should keep that in mind.
Embedding an image via data: URL
Another possible way to include images is via the data: url. Information URLs let you to completely define an image equally a Base64 encoded string of characters directly in your lawmaking.
var img = new Image ( ) ; // Create new img element img.src = 'information:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==' ;
Ane reward of data URLs is that the resulting image is available immediately without some other round trip to the server. Another potential advantage is that information technology is also possible to encapsulate in ane file all of your CSS, JavaScript, HTML, and images, making it more portable to other locations.
Some disadvantages of this method are that your image is non cached, and for larger images the encoded url can get quite long.
Using frames from a video
You can also use frames from a video beingness presented by a <video>
element (even if the video is not visible). For example, if y'all take a <video>
chemical element with the ID "myvideo", you can do this:
part getMyVideo ( ) { var canvass = document. getElementById ( 'sheet' ) ; if (canvass.getContext) { var ctx = canvass. getContext ( '2d' ) ; render certificate. getElementById ( 'myvideo' ) ; } }
This returns the HTMLVideoElement
object for the video, which, equally covered before, is i of the objects that can be used as a CanvasImageSource
.
Cartoon images
Once we accept a reference to our source image object we can employ the drawImage()
method to return information technology to the canvas. Equally we will see later on the drawImage()
method is overloaded and has several variants. In its most bones form it looks like this:
-
drawImage(image, x, y)
-
Draws the
CanvasImageSource
specified by theimage
parameter at the coordinates (x
,y
).
Annotation: SVG images must specify a width and height in the root <svg> element.
Example: A elementary line graph
In the following example, nosotros will utilise an external image as the backdrop for a small line graph. Using backdrops can make your script considerably smaller because we tin can avert the demand for code to generate the background. In this example, we're only using one paradigm, so I employ the prototype object's load
outcome handler to execute the cartoon statements. The drawImage()
method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas.
office describe ( ) { var ctx = document. getElementById ( 'canvas' ) . getContext ( '2d' ) ; var img = new Image ( ) ; img. onload = office ( ) { ctx. drawImage (img, 0 , 0 ) ; ctx. beginPath ( ) ; ctx. moveTo ( 30 , 96 ) ; ctx. lineTo ( 70 , 66 ) ; ctx. lineTo ( 103 , 76 ) ; ctx. lineTo ( 170 , xv ) ; ctx. stroke ( ) ; } ; img.src = 'backdrop.png' ; }
The resulting graph looks like this:
Scaling
The second variant of the drawImage()
method adds two new parameters and lets us place scaled images on the canvas.
-
drawImage(image, ten, y, width, height)
-
This adds the
width
andheight
parameters, which bespeak the size to which to calibration the prototype when drawing information technology onto the canvas.
Example: Tiling an epitome
In this instance, we'll utilise an paradigm as a wallpaper and repeat it several times on the canvass. This is done by looping and placing the scaled images at different positions. In the code below, the first for
loop iterates over the rows. The 2nd for
loop iterates over the columns. The epitome is scaled to one third of its original size, which is 50x38 pixels.
Note: Images can get blurry when scaling upward or grainy if they're scaled down too much. Scaling is probably best not washed if you've got some text in it which needs to remain legible.
office draw ( ) { var ctx = document. getElementById ( 'canvas' ) . getContext ( '2d' ) ; var img = new Image ( ) ; img. onload = function ( ) { for ( var i = 0 ; i < 4 ; i++ ) { for ( var j = 0 ; j < three ; j++ ) { ctx. drawImage (img, j * 50 , i * 38 , 50 , 38 ) ; } } } ; img.src = 'rhinoceros.jpg' ; }
The resulting canvas looks like this:
Slicing
The 3rd and final variant of the drawImage()
method has 8 parameters in add-on to the image source. It lets us cut out a section of the source image, then scale and describe it on our canvas.
-
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
-
Given an
prototype
, this function takes the expanse of the source image specified by the rectangle whose tiptop-left corner is (sx
,sy
) and whose width and pinnacle aresWidth
andsHeight
and draws information technology into the canvas, placing it on the canvas at (dx
,dy
) and scaling it to the size specified bydWidth
anddHeight
.
To really understand what this does, information technology may help to look at this image:
The kickoff iv parameters define the location and size of the slice on the source prototype. The last four parameters ascertain the rectangle into which to draw the epitome on the destination sail.
Slicing can be a useful tool when yous want to make compositions. Yous could have all elements in a unmarried prototype file and use this method to blended a complete drawing. For instance, if you want to make a chart you lot could have a PNG image containing all the necessary text in a single file and depending on your data could alter the scale of your chart adequately easily. Another advantage is that yous don't need to load every image individually, which can improve load performance.
Example: Framing an paradigm
In this example, we'll employ the same rhino as in the previous example, simply we'll slice out its caput and composite information technology 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 blastoff channel, unlike GIF and eight-bit PNG images, information technology can be placed onto any background without worrying about a matte color.
<html > <body onload = " depict ( ) ; " > <sheet id = "sheet" width = "150" tiptop = "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" top = "150" > </div > </body > </html >
function describe ( ) { var sheet = certificate. getElementById ( 'canvas' ) ; var ctx = canvas. getContext ( '2d' ) ; // Draw slice ctx. drawImage (document. getElementById ( 'source' ) , 33 , 71 , 104 , 124 , 21 , twenty , 87 , 104 ) ; // Draw frame ctx. drawImage (document. getElementById ( 'frame' ) , 0 , 0 ) ; }
We took a dissimilar approach to loading the images this time. Instead of loading them by creating new HTMLImageElement
objects, we included them every bit <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.
The script itself is very uncomplicated. Each <img>
is assigned an ID attribute, which makes them easy to select using document.getElementById()
. Nosotros and then use drawImage()
to slice the rhino out of the first image and calibration him onto the canvas, then draw the frame on top using a second drawImage()
call.
Fine art gallery example
In the final example of this chapter, nosotros'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 epitome and a frame is drawn around information technology.
In this case, every image has a fixed width and peak, as does the frame that's fatigued effectually them. You could raise the script so that it uses the image's width and peak to make the frame fit perfectly effectually information technology.
The code beneath should be cocky-explanatory. Nosotros loop through the document.images
container and add new canvas elements appropriately. Probably the but thing to note, for those non so familiar with the DOM, is the utilize of the Node.insertBefore
method. insertBefore()
is a method of the parent node (a table jail cell) of the element (the image) before which we want to insert our new node (the sheet element).
<html > <body onload = " describe ( ) ; " > <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" elevation = "150" > </torso > </html >
And here's some CSS to make things wait squeamish:
body { groundwork : 0 -100px echo-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 ( var i = 0 ; i < document.images.length; i++ ) { // Don't add together a canvas for the frame image if (document.images[i] . getAttribute ( 'id' ) != 'frame' ) { // Create canvas element canvas = document. createElement ( 'canvas' ) ; sail. setAttribute ( 'width' , 132 ) ; canvass. setAttribute ( 'height' , 150 ) ; // Insert earlier the image document.images[i] .parentNode. insertBefore (canvass,certificate.images[i] ) ; ctx = canvas. getContext ( '2d' ) ; // Depict paradigm to canvas ctx. drawImage (document.images[i] , 15 , twenty ) ; // Add together frame ctx. drawImage (certificate. getElementById ( 'frame' ) , 0 , 0 ) ; } } }
Controlling paradigm scaling beliefs
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 apply of paradigm smoothing algorithms when scaling images within your context. By default, this is true
, meaning images will be smoothed when scaled. Y'all can disable this feature similar 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
0 Response to "Html5 Canvas Draw Image in Circle"
Enregistrer un commentaire