HTML Canvas – Adding Text ”; Previous Next We have seen how to draw shapes as well as style them inside the Canvas element. We will now have a look at how to draw text in the Canvas element. Drawing Text To render text on the Canvas element, there are two methods available and are listed in the below table. S.No Method & Description 1 fillText(text, x, y, maximum_width) When this method is used, the given text is inserted into the Canvas at position (x, y) and is filled. We can leave the maximum width parameter without assigning a value (or) give a value to draw text with the given width. 2 strokeText (text, x, y, maximum_idth) This method draws stroked text at the given position (x, y) inside the Canvas element. We can also give a width parameter to draw for the text or leave it where default size is considered. Example Let us use font property to draw the text by the text drawing methods to understand it clearly. The following code demonstrates how text is drawn on the Canvas using the available methods. <!DOCTYPE html> <html lang=”en”> <head> <title>drawing text</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”text();”> <canvas id=”canvas” width=”550″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function text() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.font = ”55px Verdana”; context.fillText(”This text is filled”, 10, 50); context.strokeText(”This text is stroked”, 10, 100); } </script> </body> </html> Output The output for the following code is Styling text We can style the text drawn on Canvas using the styling properties. We have already seen the font property in the above example. Four properties can be used to style text on Canvas and each of them is listed in the below table. S.No Property & Description Accepted Values 1 font The text size and font style are set using this property. The default value is 10px size and font style is sans-serif. The text size is taken in pixels and the font style is taken in string. If there is any error in initializing, the font property given is ignored. Canvas.font=”text_size font_style”; 2 textAlign This property can be used to set the position of text in Canvas. The default position of the text is ”start”. It only changes horizontal alignment. ”start”, ”end”, ”left”, ”right”, ”center”. 3 textBaseline This property is used to alter the baseline alignment of the canvas text. The default value is ”alphabetic”. It sets the vertical alignment of the text. ”top”, ”hanging”, ”middle”, ”alphabetic”, ”ideographic”, ”bottom”. 4 direction It sets the directionality for the Canvas text. The default value is ”inherit”. ”ltr”, ”rtl”, ”inherit”. Example 1 Following example demonstrates font and textAlign properties of text in HTML5 Canvas. <!DOCTYPE html> <html lang=”en”> <head> <title>styling text</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”text();”> <canvas id=”canvas” width=”550″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function text() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.font = “25px Verdana”; context.textAlign = “start”; context.fillText(context.textAlign, 10, 75); context.textAlign = “end”; context.fillText(context.textAlign, 500, 75); context.textAlign = “left”; context.fillText(context.textAlign, 140, 75); context.textAlign = “right”; context.fillText(context.textAlign, 390, 75); context.textAlign = “center”; context.fillText(context.textAlign, 275, 75); } </script> </body> </html> Output The following code returns output as Example 2 Following code implements textBaseline property for all the available values. <!DOCTYPE html> <html lang=”en”> <head> <title>styling text</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”text();”> <canvas id=”canvas” width=”700″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function text() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.font = “25px Verdana”; context.textBaseline = “top”; context.strokeText(context.textBaseline, 0, 75); context.textBaseline = “hanging”; context.strokeText(context.textBaseline, 80, 75); context.textBaseline = “middle”; context.strokeText(context.textBaseline, 210, 75); context.textBaseline = “alphabetic”; context.strokeText(context.textBaseline, 310, 75); context.textBaseline = “ideographic”; context.strokeText(context.textBaseline, 450, 75); context.textBaseline = “bottom”; context.strokeText(context.textBaseline, 610, 75); } </script> </body> </html> Output The output for the following code is Example 3 We will demonstrate text direction in the following example. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″> <meta http-equiv=”X-UA-Compatible” content=”IE=edge”> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> <title>styling text</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”text();”> <canvas id=”canvas” width=”600″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function text() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.font = “25px Verdana”; context.fillText(”direction-”, 150, 50); context.direction = ”rtl”; context.fillText(”direction-”, 150, 130); } </script> </body> </html> Output The output for the following code is Measuring text This method is used to obtain more details about the text. It allows us to measure the text. The method used to achieve this is measureText(”text_string”) – This method returns a text object containing the width of input text in pixels when drawn as the current style given. Example Following code demonstrates the measureText() method. The implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>styling text</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”text();”> <canvas id=”canvas” width=”600″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function text() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.font = “25px Verdana”; context.strokeText(“hello”, 10, 50); var text = context.measureText(”hello”); window.alert(text.width); } </script> </body> </html> Output The output returned by the code is Print Page Previous Next Advertisements ”;
Category: html Canvas
HTML Canvas – Element
HTML Canvas – Element ”; Previous Next Canvas element is the outline of the HTML Canvas tag which is defined by the HTML code and is styled using the CSS. We can render graphics inside the canvas using JavaScript code by a context object. Canvas element is equipped with the interface HTMLCanvasElement containing properties and methods to manipulate the layout as well as the features supported by the Canvas element. The properties and methods available to create and modify the Canvas element are given in the below table. Properties Following are various properties of HTML Canvas Element − S.No Property and Description 1 Canvas The canvas property of CanvasRenderingContext2D interface provides the canvas outline by using CSS styling. Without styling, we cannot see it on the webpage even though it is formed. 2 Width This property helps us to set the width for the Canvas layout. 3 Height This property helps us to set the height for the Canvas layout. Methods Below given is the list of methods provided by the HTML Canvas Element class − S.No Method & Description 1 getContext() This method refers to the context of the drawing on the Canvas element. We give the context type and attributes as the parameters which are displayed on the Canvas. Print Page Previous Next Advertisements ”;
HTML Canvas – Adding Images
HTML Canvas – Adding Images ”; Previous Next The best feature of the Canvas element is it can accept images and use them. Canvas element accepts all external image files to display on the webpage and we can use the images produced by other Canvas elements which are available on the same webpage. Importing an image to the Canvas is a two-step process Retrieve the image using any of the available options. Draw the image onto the canvas element using the drawImage() function. Retrieving images The Canvas API can use any of the following data types as an image source. HTMLImageElement − These images are created using Image() constructor or the <img> tag of HTML. SVGImageElement − The images are generally embedded using the <image> element. HTMLVideoElement − It uses HTML <video> element as the image source and grabs the current video frame and uses it as the required image. HTMLCanvasElement − We can use another Canvas element that is available on the same webpage as the image source. To retrieve images onto the Canvas element and use them, there are six possible ways, and each is mentioned below. Images from the same page We can obtain all the images available on the pages using the DOM model. To find all the available images, document.images collection must be accessed. To use one of the available images, we can use document.getElementsByTagName() method or document.getElementById() method if we know the ID of that specific image. Images from other domains To retrieve an image that is available in the other domain, we will use the tag and call the image to the Canvas element using the drawImage() function. Make sure the image is transferrable, or else the canvas may get tainted. Images using other Canvas elements When we retrieved the images available on same page using document.getElementsByTagName() or document.getElementById() method, we can use the same to retrieve images from other Canvas elements also. To achieve this, we must make sure the source canvas is already drawn before it is used by the target canvas. Embedding the image using URL To include an image to the canvas, we can directly add the image URL to the code and access it. The main advantages of using URL are that the image can be accessed very fast than other methods as it does not have to get server access again and make it portable to other locations. If the image is not perfectly accessed by URL, it might not be displayed on canvas. A simple code snippet to access the image using the URL is given below // Creating an image element var image = new Image(); // Accessing the image using URL image.src = ”https://www.tutorialspoint.com/scripts/img/logo-footer.png”; Generate frames from video We can get image frames from the video using <video> element. For example, if we have a video element having id as smallvideo, we can get frames from it and use it as an image. A small code snippet is given below to demonstrate image retrieval // function to get image frame function frameFromVideo() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); return document.getElementById(”smallvideo”); } Building image from scratch We can use image() constructor to create the image and access it using its path. The image starts loading after the image path is fed to the constructor. A small code is given below to show how an image is built from scratch using the source path. // Create new img element var image = new Image(); // to avoid exceptions image.addEventListener(”load”, function() { // add draw image code statements here }, false); // give image source path image.src = ”imageaddress.png”; Draw images HTML5 Canvas element is equipped with a default method to draw images on the canvas. The method is given below S.No Method & Description 1 drawImage() This method draws the image onto the canvas element. The method takes three types of input parameters and is given accordingly. 2 drawImage(image, x, y) This method takes the image as the first parameter and draws it at the point ( x, y) on Canvas. 3 drawImage(image, x, y, width, height) This method draws the image given as a parameter on the canvas at the point (x, y) with the given width and height. This method is generally used for scaling the image. 4 drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) This method contains source points and destination points with width and height for the source as well as the destination. This method is used for slicing the image. Example Following example code implements how an image is drawn into the Canvas element. <!DOCTYPE html> <html lang=”en”> <head> <title>Images</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”image();”> <canvas id=”canvas” width=”450″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function image() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); var image = new Image(); image.onload = function() { context.drawImage(image, 50, 50); }; image.src = ”https://www.tutorialspoint.com/html5/images/logo.png”; } </script> </body> </html> Output The code renders the image onto canvas and is shown below Scaling and Slicing Image scaling is very useful when there is a need to contain the space of canvas so that other shapes or graphics can be constructed inside the Canvas element. Scaling may cause image blurriness, so the parameters should be given correctly. The method which helps us to perform scaling on the Canvas image is drawImage( image, x, y, width, height); Example for scaling Following example demonstrates how scaling can be performed on the same image by varying width and height parameters
HTML Canvas – Adding Styles
HTML Canvas – Adding Styles ”; Previous Next Similar to colors we can also add various stlyes to difference shapes available in HTML5 Canvas. Let us see them one by one. Styles to Lines One way to draw a line in HTML5 is to use the lineTo path element. We can also beautify these lines using the various style properties. Since most of the objects we create on canvas are drawn using lines we can stryle these objects using the line properties. The properties that are used for styling lines are listed in the below table. S.No Property & Description Sample image 1 ineWidth The width of the lines drawn can be assigned using this property. The thickness value of any line by default is 1 unit. 2 lineCap This property is generally used to style the ends of the line. There are three accepted input values for the property which are ”butt”, ”round” and ”square”. The default value is always ”butt”. 3 lineJoin When two lines are about to be joined, this property can be used to set the appearance of the corners where lines are joined. The values accepted by the property are ”miter”, ”bevel”, and ”round”. The default value of the property is ”miter”. The property does not affect the lines as there is no joining area added. 4 miterLimit The thickness of the junction is changed using the property when two angles join at a sharp angle. This property determines the distance of outside connection to which inside connection point can be placed. The default value is 10 but the possible values completely depend on the lines used. 5 lineDashOffset This specifies the dash pattern for the lines. This is used to make dotted and dash lined patterns. We can also use it in setLineDash() method and create animation effects. Apart from these properties, two other methods can be used to apply styles for lines. The getLineDash() method − This returns the current line-dash pattern containing an even number of positive numbers. The setLineDash() method − To set the dash lines to create a shape or pattern using Canvas, this method is used. It takes segment array as inputs which consist of some line values. If nothing is given, a simple stroked line is given as output. Example Following code demonstrates lineWidth and lineCap properties. The implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Styling lines</title> <style></style> </head> <body onload=”linestyles();”> <canvas id=”canvas” width=”300″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function linestyles() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(”2d”); // lineWidth property context.moveTo(30, 30); context.lineTo(30, 150); context.lineWidth = 5; context.stroke(); // linecap round property context.beginPath(); context.moveTo(80, 30); context.lineTo(80, 150); context.lineWidth = 10; context.lineCap = ”round”; context.stroke(); context.closePath(); // linecap butt property context.beginPath(); context.moveTo(130, 30); context.lineTo(130, 150); context.lineWidth = 10; context.lineCap = ”butt”; context.stroke(); context.closePath(); // linecap square property context.beginPath(); context.moveTo(180, 30); context.lineTo(180, 150); context.lineWidth = 10; context.lineCap = ”square”; context.stroke(); context.closePath(); } </script> </body> </html> Output The output for the following code is given below. Example Following code demonstrates the lineJoin and miterlimit properties. The miterlimit property is demonstrated with values ”2 units” and ”20 units” respectively. The code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Styling lines</title> <style></style> </head> <body onload=”linestyles();”> <canvas id=”canvas” width=”600″ height=”400″ style=”border: 1px solid black;”></canvas> <script> function linestyles() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(”2d”); // linejoin round property context.moveTo(30, 30); context.lineTo(30, 150); context.lineTo(150, 150); context.lineTo(150, 30); context.lineJoin = ”round”; context.lineWidth = 10; context.stroke(); // linejoin bevel property context.beginPath(); context.moveTo(200, 30); context.lineTo(200, 150); context.lineTo(320, 150); context.lineTo(320, 30); context.lineJoin = ”bevel”; context.lineWidth = 10; context.stroke(); context.closePath(); // linejoin miter property context.beginPath(); context.moveTo(370, 30); context.lineTo(370, 150); context.lineTo(490, 150); context.lineTo(490, 30); context.lineJoin = ”miter”; context.lineWidth = 10; context.stroke(); context.closePath(); // miterlimit property with value 2 context.beginPath(); context.moveTo(50, 200); context.lineTo(120, 350); context.lineTo(190, 200); context.miterLimit = 2; context.lineJoin = ”miter”; context.lineWidth = 25; context.stroke(); context.closePath(); // miterlimit property with value 20 context.beginPath(); context.moveTo(250, 200); context.lineTo(320, 350); context.lineTo(390, 200); context.miterLimit = 20; context.lineJoin = ”miter”; context.lineWidth = 25; context.stroke(); context.closePath(); } </script> </body> </html> Output Following code gives the output as Example The following example uses setLineDash method and lineDashOffset property value to specify dish patterns for drawing shapes using lines. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Styling lines</title> <style></style> </head> <body onload=”linestyles();”> <canvas id=”canvas” width=”350″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function linestyles() { var canvas = document.getElementById(“canvas”); var ctx = canvas.getContext(”2d”); var offset = 0; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.setLineDash([50, 10]); ctx.lineDashOffset = offset; ctx.strokeRect(10, 10, 250, 125); } function animate() { offset++; if (offset > 25) { offset = 0; } draw(); setTimeout(animate, 50); } animate(); } </script> </body> </html> Output The code returns the output as shown below. Paste the code in the editor to see the animation effect. Gradients We can simply fill and stroke shapes using gradients just like drawing a shape on a Canvas element. There are three types of gradients available in Canvas, they are linear, radial, and conic. We can create gradient objects using three methods. Each method is listed in the below table. S.No Method & Description 1 createLinearGradient(x1, y1, x2, y2) Creates a linear gradient object having starting point as (x1,y1) and an end point as (x2,y2). 2 createRadialGradient(x1, y1, r1, x2, y2, r2) This method is used for creating a radial gradient object. It takes two circles as its parameters where the first circle radius is r1 and the center
HTML Canvas – Paths
HTML Canvas – Paths ”; Previous Next Path is a continuous mapping of points as a trial which does not have repeating vertices and does can go in any angle until the final destination point is reached. The interface CanvasRenderringContext2D and Path2D contains properties and methods to add paths onto the canvas element using the context object of interface. The interface can be used for adding paths as well as closing them on the <canvas> element. The properties and methods available to add paths and draw shapes inside the Canvas element are given in the below table. S.No Method & Description 1 addPath() This method can be used to add an extra path for the current path. 2 arc() The arc() method of Canvas API can be used to draw circular arcs to the path started. 3 arcTo() The arcTo() method of Canvas API can be used to draw circular arcs to current path with given control points and radius as parameters. 4 beginPath() When we have to draw graphics on Canvas element using paths, we call this method to create a new path. 5 bezierCurveTo() The method bezierCurveTo() of CanvasRenderingContext2D interface draws 6 clip() This method is used to clip a region of path and draw another graphics in it. 7 closePath() The method closePath() closes the current path by doing the required operations. 8 drawFocusIfNeeded() To add focus to an existing path or a path that is about to be created, this method can be called by the interface. 9 ellipse() This method is used to draw an elliptical arc on the drawing surface of Canvas element. 10 fill() This method fills the current or given path with black by default unless fillStyle property is given. 11 isPointInPath() To check whether a point is inside or with the path, we use this method. It takes the point as parameter and returns Boolean value. 12 isPointInStroke() This method of Canvas 2D API verifies whether the given point is inside a stroked path or not and returns Boolean value (true or false). 13 moveTo() The context object moves the sub path to the given co-ordinates by parameters. 14 Path2D() This constructor method creates a Path2D object from which all the shapes can be invoked and drawn onto the Canvas element. 15 quadraticCurveTo() This method draws a quadratic Bezier curve by using the path context. 16 scrollPathIntoView() This method of Canvas 2D API when called, scrolls the available path into view when it is passed as the parameter. 17 stroke() This method of Canvas API adds strokes to the current path or shape which is drawn inside the Canvas element. Print Page Previous Next Advertisements ”;
HTML Canvas – 2D Shapes Using Path Elements ”; Previous Next In this chapter we are going to discuss how to draw various 2D shapes using various path elements of HTML5. There is a method named rect() used to create rectangles in the Canvas element. It uses the concept of the path, and its syntsx is rect(x, y, width, height) This method draws a rectangle whose top-left corner is specified by (x, y) with a given width and height. To execute this method, moveTo() must be called with parameters x and y so the pointer moves to the coordinates from which the rectangle can be drawn. In the same way we can create other 2D shapes using these path elements.The steps involved in making shapes using paths in the Canvas element are Step 1 − Creating the path: This step is usually done using the beginPath() function which creates the path by which the actual shape is constructed. Step 2 − Using drawing commands to draw into the path: To draw a shape using Canvas, we use functions like lineTo() and moveTo() to draw the required path. Step 3 − Use methods like stroke or fill to construct the shape: After drawing the path, we use fill() and stroke() methods to make the path shape generated more understandable. Then we will complete the path by using the closePath() function. Drawing Triangles Mathematically, the Intersection of three lines is considered a triangle. It consists of three intersected lines at a particular angle. The intersected lines are called vertices of the triangle. To draw a triangle, we must use Path functions. The triangle is drawn using three lines by the lineTo() function. We first begin the path and move to the point where we draw a line and then use lineTo() until a triangle is formed. We must make sure the coordinates given to the functions must form a triangle. We can add properties to the triangle formed by using the required functions such as shape, gradient, etc. The syntax of lineTo() function is Canvas.lineTo(x, y); Where the parameters involved are x and y which denotes the point to which the line is to be drawn. We have to first initialize the starting point using the moveTo() function. Example Following example draws a triangle using path operations. The program code is given below <!DOCTYPE html> <html lang=”en”> <head> <title>Triangle</title> </head> <body onload=”triangle();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> <script> function triangle() { var canvas = document.getElementById(”canvas”); if (canvas.getContext) { var ctx = canvas.getContext(”2d”); ctx.beginPath(); ctx.moveTo(50, 100); ctx.lineTo(100, 50); ctx.lineTo(150, 100); ctx.lineTo(50, 100); ctx.fillStyle = “blue”; ctx.fill() } } </script> </body> </html> Output The triangle formed for the above code is shown below. We can play with the coordinates and make other triangles such as right-angled and isosceles triangles. We can also add the closePath() function at the end. If we do not give closePath() at the end of the script, the path is still running and is not stopped. Drawing Lines A line is a shape formed when two points are joined with a minimum distance between them. It is a common mathematical shape that is used to draw most of the shapes in geometry. To draw a line using HTML5 Canvas by using Paths, we should use two methods, moveTo(x, y) and lineTo(x, y). To identify the line on Canvas, we must use stroke() or fill(). The moveTo() method defines the position of the cursor to draw on the canvas, whereas the lineTo() method defines the coordinates of the end point of the line, and the stroke() or fill() method is used to make the line visible on the canvas element. The color of stroke() or fill() is black unless specified by the user. The syntax of the functions used to draw the line are Canvas.moveTo(x,y); The canvas cursor is moved from the origin to the point (x, y). Canvas.lineTo(x, y); A line is drawn from the cursor point to the given parameter points (x, y). Example We will work on some examples to understand it clearly. The following example will take a square on canvas and draw its diagonal using lines. The implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Line-Diagonal</title> <style> <style>body { margin: 10px; padding: 10px; } </style> </head> <body onload=”line1();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> <script> function line1() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); var x = 50; var y = 50; var width = 200; var height = 200; context.strokeRect(x, y, width, height); context.moveTo(50, 50); context.lineTo(250, 250); context.stroke(); } </script> </body> </html> Output We have first constructed a square using a rectangle on canvas with its dimensions given above and drawn a line from its top-left coordinates (x, y) to the bottom right coordinates adding the x and y values (x+width, y+height) as they are away from the origin. Refer to Canvas coordinates to understand this clearly. The output for the above code is given below. Example We will work on another example in which only lines are drawn. Let us draw the letters ”h” and ”i” using the lines. We will be using lineWidth() and strokeStyle() to make the output easily understandable and make it look attractive. The code for the program is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Line-”hI”</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”line2();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> <script> function line2() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.lineWidth = 5.0; context.beginPath(); context.strokeStyle = ”green”; context.moveTo(50, 50); context.lineTo(50, 200); context.lineTo(50, 100); context.lineTo(100, 100); context.lineTo(100, 200); context.stroke(); context.beginPath(); context.strokeStyle = ”green”; context.moveTo(200, 50); context.lineTo(200, 200); context.stroke(); } </script> </body> </html> Output The output of
HTML Canvas – Transformations ”; Previous Next We have learned about how the Canvas grid is used to draw shapes using the coordinates. We can use transformations to translate the position of origin to a different position, rotate and scale the grid. Save and restore are two indispensable methods that help us to draw complex drawings. Each of the methods is described below. S.No Method & Description 1 Save() This method is called to save the current state of the Canvas element. It saves the entire state of canvas. 2 Restore() This method rollbacks the last saved canvas state. Canvas uses the stack to store all the modifications done to the canvas element. The save() method can be called as many times as the user need and is pushed into the stack. Each time we call the restore() method, the last saved state is popped off the stack and is restored into the canvas. Example The following example illustrates how save() and restore can be implemented in the Canvas element. <!DOCTYPE html> <html lang=”en”> <head> <title>Transforming </title> </head> <body onload=”transform();”> <canvas id=”canvas” width=”300″ height=”250″ style=”border: 1px solid black;”></canvas> <script> function transform() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.fillStyle = ”orange”; context.fillRect(40, 40, 200, 150); context.save(); context.fillStyle = ”white”; context.fillRect(55, 55, 170, 120); context.save(); context.fillStyle = ”green”; context.fillRect(70, 70, 140, 90); context.restore(); context.fillRect(85, 85, 110, 60); context.restore(); context.fillRect(100, 100, 80, 30); } </script> </body> </html> Output The output of the following code is Translate The translate() method can be used to shift the origin of the Canvas grid and draw the graphics inside. The method is given below Translate(x, y)− The method moves the canvas origin and the grid to another position. ”x” indicates the horizontal distance to move, and ”y” indicates the vertical distance to move. Example The following example demonstrates the functioning of translate() method. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Transforming </title> </head> <body onload=”translate();”> <canvas id=”canvas” width=”500″ height=”400″ style=”border: 1px solid black;”></canvas> <script> function translate() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.fillStyle = ”green”; context.fillRect(25, 25, 150, 100); context.translate(100, 100); context.fillStyle = ”blue”; context.fillRect(125, 125, 150, 100); } </script> </body> </html> Output The output returned by the above code is Rotate The rotate() method can be used to rotate the Canvas element to a certain angle using origin coordinates as the point of reference. The method is given below rotate(angle) − The canvas element is rotated at an angle passed as the parameter in the rotate() method. To change the origin position, we can use the translate() method. The angles should be given in radians. Example Following example demonstrates the rotate() method and shows how the angle change results the drawing shapes. <!DOCTYPE html> <html lang=”en”> <head> <title>Transforming </title> </head> <body onload=”rotate();”> <canvas id=”canvas” width=”350″ height=”250″ style=”border: 1px solid black;”></canvas> <script> function rotate() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.fillStyle = ”green”; context.fillRect(25, 25, 150, 100); context.translate(100, 100); context.rotate(75); context.fillStyle = ”blue”; context.fillRect(25, 25, 150, 100); } </script> </body> </html> Output The shapes generated by the above image are Scale and Transform The transformation methods scaling, and transforms are mainly used to change the Canvas element grid by varying units of the canvas and transforming the positions. The methods are given below. scale(x, y) − scale method is used to increase or decrease the size of the Canvas grid. By default, one unit of the canvas element is exactly one pixel. The scale method takes all float values and the values less than 1.0 reduce the unit size and more than 1.0 increase the unit size of Canvas which is used to scale the grid. Example for scaling Following example scales the canvas grid and draws a text using the available functions. The implementation code is given below <!DOCTYPE html> <html lang=”en”> <head> <title>Transforming </title> </head> <body onload=”scale();”> <canvas id=”canvas” width=”600″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function scale() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.scale(1.5, 3.0); context.font = ”50px Verdana”; context.fillText(”TutorialsPoint”, 10, 50); } </script> </body> </html> Output The following code returns the canvas text as Transformation methods can be used to directly modify the transformation matrix. The methods available to achieve transforms are given below. Transform(a, b, c, d, e, f) − This method multiplies the current matrix with the transformation matrix. The parameters involved are a – Horizontal scaling b – Horizontal skewing c – Vertical skewing d – Vertical scaling e – Horizontal moving f – Vertical moving The setTransform(a, b, c, d, e, f) method: It resets the current transform to the identity matrix and calls the transform() method to set the specified transform using parameters. The resetTransform() method − It changes the current matrix to the identity matrix. Transform example The following code implements transform methods on the text. <!DOCTYPE html> <html lang=”en”> <head> <title>Transforming </title> </head> <body onload=”transform();”> <canvas id=”canvas” width=”300″ height=”350″ style=”border: 1px solid black;”></canvas> <script> function transform() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.font = ”40px Verdana”; context.strokeText(”Transform”, 50, 50); context.transform(0.5, 1.0, 1.5, 1.0, 0.5, 0); context.font = ”40px Verdana”; context.strokeText(”Transform”, 50, 50); } </script> </body> </html> Output The output of the above code is Print Page Previous Next Advertisements ”;
HTML Canvas – Introduction
HTML Canvas – Introduction ”; Previous Next Canvas is an HTML element that can perform dynamic generation of 2D shapes and bitmap images using JavaScript. HTML Canvas is a great alternative for drawing pictorial data such as graphs, charts, and maps inside a web page. It is a low-level procedural model which updates in the form of a bitmap. The Canvas element is only the basic rectangular-shaped container for graphics, which is usually done using JavaScript. The shapes or any other graphics implementation inside the Canvas element can be done using JavaScript. HTML Canvas element is an HTML tag like the div, a, or table, with the exception that its contents are rendered using JavaScript. Why Canvas? There are more than 1.2 billion websites available today which are unique from each other and have various features involved. The canvas element is specially designed to make visual content that can be uniquely applied to develop website UI and make them more attractive for users. It is very easy to learn and requires a knowledge base of HTML and JavaScript. Canvas and <img> tag? The canvas element looks like the HTML5 image <img> element at first, except for not having “src” and “alt” attributes. Unlike the image element, the canvas element requires the closing tag. The canvas element does have only two attributes which are width and height. To design graphics using Canvas, we must use JavaScript. Dimensions of Canvas By default, canvas does not have a border and no content. The width and height can be declared in the element or can be manually adjusted using the DOM properties of JavaScript. When no width and height attributes are given in the code, it is set to default where width is 300 pixels and height is 150 pixels. The element can also be styled by CSS, using the Style tag, and can also give parameters such as border color and thickness. If the CSS Style or dimensions are given do not match with the initial Canvas, it will appear as a distorted rectangle. Even though, the Canvas element can be styled using CSS, the actual drawing on the Canvas remains ineffective and can be modified using Scripting languages Canvas element and Canvas context While using canvas, it is important to understand the basic difference between the canvas element and the canvas context, as often people get these both confused. The canvas element is the actual DOM node that is embedded in the HTML page. A canvas context is an object with properties and methods that you can use to render graphics inside the canvas element. The context can be 2D or 3D (by using WebGL). We can assign only one context to the canvas element using the getContext() function. Changing context multiple times in the same canvas may result in the same object context. Structure of Canvas element A simple <canvas> element is defined using the attributes id, width, height, and style to observe the canvas border. The main thing to be identified here is that without giving any style to the canvas, it cannot be observed on the webpage even though it is formed. A simple canvas tag is shown below. <canvas id=”canvas” width=”555″ height=”555″ style=”border:2px solid black;”> This browser neither have JavaScript enabled nor support HTML5 canvas tag. </canvas> The canvas element is identified using id or class to render graphics in the future using JavaScript. In the above example, a canvas is built with dimensions 555×555 with the border colored black. The sentence inserted between the canvas tag is displayed when there is an error that causes the canvas to not display. The text displayed on the page makes the user identify that there is an error in displaying the canvas. The canvas outline is shown below. HTML5 Canvas vs Scalable Vector Graphics (SVG) Scalable Vector Graphics (SVG) is an XML-based markup language developed by World Wide Web Consortium (W3C) in 1999 for visualizing 2D-based vector graphics. It is an earlier standard for drawing shapes and designing graphics in browsers. SVG is a text-based, open Web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including CSS, DOM, JavaScript, and SMIL. SVG-format vector images can be easily localized by updating the text within them, without the need of any graphical editor to do so. The HTML Canvas element works like the SVG with some differences mentioned below. HTML Canvas Scalable Vector Graphics (SVG) Canvas represents 2D images using a rectangular grid of pixels. SVG represents 2D images using geometric shapes designed from cartesian planes such as points, lines, and curves. Canvas objects are drawn in the immediate mode where if any error occurs the canvas becomes irregular. SVG objects are remembered by DOM and are rendered to bitmap to use in case of change in attributes. Canvas has poor scalability as it is a low-level procedural model. SVG has high scalability, we can print high-quality graphics at any resolution. Canvas can be modified using script only. SVG can be modified using CSS and script. Canvas only has a single graphic element. SVG has multiple elements which are a part of the page”s DOM tree. Canvas element tag is defined by <canvas>. SVG element is defined by <svg> tag. The canvas element has two sizes. The first one is the size of the element itself which can be altered by changing the element”s width and height attributes. Another size is the element”s drawing surface. CSS attributes can only change an element”s size, but the drawing surface remains unaffected. The Canvas element can be designed in two
HTML Canvas – Drawing 2D Shapes ”; Previous Next Till now we have seen how to draw the Canvas element using attributes. Now we will be building simple 2D shapes and rendering them inside the Canvas element. The Canvas element supports only two primitive shapes, rectangles, and paths by which all the remaining shapes can be drawn easily. There are many drawing functions available which makes it easier to construct all the remaining shapes from paths. HTML5 Canvas can be used to draw 2D shapes which are used further to develop graphical objects. It is possible to draw all kinds of shapes using Canvas elements including complex shapes such as polygons and curves. Each of the shapes that can be drawn using Canvas is drawn using basic design features such as fill and stroke. These features help us to add graphics to the hollow 2D shapes and make beautiful visualizations. Before drawing shapes on Canvas, we must understand the grid concept to efficiently construct graphical shapes. The Canvas element can be accessed to draw various shapes using the following steps Find the Canvas element. Create a Drawing object using JavaScript to draw inside the canvas element. Draw on the canvas using script objects. Almost all 2D shapes can be drawn using the Canvas element which is further styled by some common functions and Event listeners such as gradient, colors, etc. These help in increasing user interactivity and visual content understanding. The shapes that can be drawn using the Canvas element are Rectangles Squares (using rectangle functions) Circles ellipse Triangles Curves Lines Arcs Canvas co-ordinate space (Grid) To draw any shape using the Canvas element, we must understand the concept of a Grid. The grid shows the structural representation of the Canvas element and helps us to understand how a shape is inserted into the canvas. The whole Canvas element is divided into squares with a side of 1 pixel. The coordinates of the outer Canvas element are considered to draw the elements in the canvas at different positions. The shapes are generally inserted into the Canvas such that their coordinates lie between origin and the canvas width and height. Below is the image of the grid and how a square is inserted into the Canvas element. Normally, one unit inside the Canvas is considered as 1 pixel. The origin of this grid is positioned in the top left corner with coordinates (0,0). All elements are placed using this origin and the bottom-left coordinates (canvas width, canvas height). So, the position of the top left corner of the green square inside the Canvas element becomes x pixels from the left and y pixels from the top, at coordinate (x, y). Drawing rectangles using HTML5 Canvas Rectangles can be drawn in two ways. The first one is by using four lines (two parallel lines each representing width and height of the rectangle) which makes it complex and not generic. The other approach to drawing rectangles is by using the available functions. Three functions can be used to draw rectangles using Canvas by considering the coordinates of the shape. We can draw rectangles using three functions namely S.No Method & Description 1 fillRect(x, y, width, height) This function creates a filled rectangle. 2 strokeRect(x, y, width, height) This function creates a stroked/hollow rectangle. 3 clearRect(x, y, width, height) This function creates a clear rectangle. 17 Each of these functions is used to create/draw a different type of rectangle. The parameters involved in the functions are (X, Y) − Distance from the origin. The main point from which the rectangle is drawn. Width − The width of the rectangle to be drawn. Height − The height of the rectangle to be drawn. Each of the rectangle functions is implemented below with functioning code. Creating a Fill Rectangle By using the above function, we can draw a filled rectangle. It takes the starting co-ordinates (x, y) and the width and height of rectangle as parameters. Simple syntax for the function is Canvas.fillRect(50, 50, 300, 150); Example The code to implement fillRect() is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>fillRect()</title> <style> body { margin: 10px; padding: 10px; } </style> <script> function rectangle() { var canvas = document.getElementById(”canvas”); if (canvas.getContext) { var ctx = canvas.getContext(”2d”); ctx.fillRect(50, 50, 200, 200); } } </script> </head> <body onload=”rectangle();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> </body> </html> Output The output for the following code is Creating a Stroke Rectangle A rectangular outline can be drawn using strokeRect() function. It takes the starting co-ordinates (x, y) and the width and height of rectangle as parameters. Simple syntax for the function is Canvas.strokeRect(50, 50, 300, 300); Example Following example creates a stroked rectangle <!DOCTYPE html> <html lang=”en”> <head> <title>strokeRect()</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”rectangle();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> <script> function rectangle() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); var x = 50; var y = 50; var width = 200; var height = 200; context.strokeRect(x, y, width, height); } </script> </body> </html> Output The output for the above code is Creating a Clear Rectangle It takes the starting coordinates (x,y) and the width and height of the rectangle as parameters. The simple syntax for the function is Canvas.clearRect(50, 50, 60, 60); The following function clears the specified rectangular area by making it completely transparent. To understand the function, we will be using both the functions fillRect() and strokeRect(). Following example shows
Environmental Setup
HTML Canvas – Environmental Setup ”; Previous Next One of the best applications of the canvas is that it works on any browser which is equipped with HTML5 and JavaScript support. This makes it so versatile and easy to work on. All the browsers available today such as Chrome, Opera, Mozilla, Edge, and Safari are equipped with JavaScript support. Hence any editor that can be used to display HTML and JavaScript code can be used to work with the HTML5 Canvas element. Furthermore, your browser must be permitted to access and execute JavaScript code. Below is the table which contains browser names and version numbers from which HTML5 canvas can be supported. Browser Name Canvas Support Google Chrome 4.0 and above Microsoft Edge 9.0 and above Mozilla Firefox 2.0 and above Opera 3.1 and above Apple Safari 9.0 and above The basic requirements needed for implementing 2D dynamic graphical designs and visualization effects using the Canvas element are listed below A text editor To write code in. This could be any text editor such as Visual Studio Code (VS code), Notepad++, Sublime Text, or Atom. We cannot use document editors to create the Canvas element as we cannot use JavaScript only in hybrid editors. I recommend Sublime Text or Visual Studio Code as they are very easy to script. Visual Studio Code comes with an in-built local server to run the web programs on the local server with a random port. Sublime text is equipped with easy tools which make it simpler to use and work on. There are also several online compilers such as codepen.io which make it easier to work on without downloading any IDE. Web browsers To test code in webpages and understand it”s structure. Currently, the most-used browsers are Mozilla Firefox, Google Chrome, Microsoft Edge, Opera Browser and Apple Safari. You should also test how your site performs on mobile devices and on any old browsers your target audience may still be using (such as IE 8-10). This helps to improve and understand how the Canvas element is interacted with the web page. There are also some different web browsers such as Lynx, which is a text-based terminal web browser used for seeing how your site is experienced by visually impaired users. You can also use Explorer-canvas to get canvas support through Internet Explorer. To make it work, we must include below JavaScript snippet in our code <!–[if IE]><script src = “canvas.js”></script><![endif]–> Verification Execute the following example to check if editor is working correctly or not <!DOCTYPE html> <html lang=”en”> <head> <title>Check editor</title> </head> <body> <p>Hello viewers</p> <canvas id=”canvas” width=”300″ height=”150″ style=”border: 2px solid black;”> This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled. </canvas> </body> </html> If the editor creates a web page containing the string “Hello viewers” and a small hollow rectangle, the editor is installed correctly. If the webpage does not render anything installation is not done correctly. The text available inside the Canvas tag is displayed only when the web browser does not support the Canvas element. You need to update your browser or install one which supports the Canvas element. Print Page Previous Next Advertisements ”;