HTML Canvas – Useful Resources ”; Previous Next The following resources contain additional information on HTML Canvas. Please use them to get more in-depth knowledge on this. Useful Video Courses Learn HTML Introduction to creating your first website 16 Lectures 1 hours Laurence Svekis More Detail Complete HTML and CSS Masterclass For Beginners (Complete Bootcamp Course) 51 Lectures 7 hours Emenwa Global, Ejike IfeanyiChukwu More Detail Master HTML5 and CSS3 Fundamentals Best Seller 35 Lectures 4.5 hours Stone River ELearning More Detail HTML JavaScript & AspNet C# Programming : Beginner to Expert 142 Lectures 16.5 hours Metla Sudha Sekhar More Detail Learn HTML JavaScript Restful API from scratch: Web Services Most Popular 108 Lectures 11 hours Metla Sudha Sekhar More Detail Responsive Web Development With HTML5 And CSS3 For Beginners 57 Lectures 7.5 hours Robert Nana Sarpong More Detail Print Page Previous Next Advertisements ”;
Category: html Canvas
HTML Canvas – Discussion
Discuss HTML Canvas ”; 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. Print Page Previous Next Advertisements ”;
HTML Canvas – Text
HTML Canvas – Text ”; Previous Next Text can be rendered on the Canvas element using the available methods and properties. We can also style the drawn text so that efficient graphics can be generated. The TextMetrics interface and CanvasRenderingcontext2D is used to draw and style text as well as to identify the structural properties of text rendered inside the Canvas element. The text is generally rendered using a CanvasRenderingContext2D object by available methods and also can be retrieved using read-only properties. Properties The properties available to draw and style text on the Canvas element are listed in the below table. S.No Property and Description 1 actualBoundingBoxAscent This property returns the distance from the horizontal line indicated by the baseline property to the rectangle top from which text is drawn inside the Canvas. 2 actualBoundingBoxDescent This property returns the distance from the horizontal line indicated by the baseline property to the rectangle bottom from which text is drawn inside the Canvas. 3 actualBoundingBoxLeft This property returns the distance parallel to the text baseline to the left side of bounding rectangle of text in pixels. 4 actualBoundingBoxRight This property returns the distance parallel to the text baseline to the right side of bounding rectangle of text in pixels. 5 direction The direction property specifies the direction of text which is about to be drawn onto the Canvas element. 6 font This property of Canvas API specifies the text size, style and font style of the text about to be drawn onto the Canvas element. 7 fontBoundingBoxAscent This property of the TextMetrics interface returns the distance from horizontal line of text baseline to the top of highest bounding rectangle of the text inside canvas element. 8 fontBoundingBoxDescent This property of the TextMetrics interface returns the distance from horizontal line of text baseline to the bottom of highest bounding rectangle of the text inside canvas element. 9 textAlign This property of Canvas element object specifies the text alignment to be used when drawing text. 10 textBaseline This property of Canvas element object specifies the text baseline to be used when drawing text. Methods Following are various methods available to perform various operations on the Text element of HTML Canvas. S.No Method & Description 1 fillText() This method fills the text drawn on the Canvas element. 2 MeasureText() when this method is used, the text information which is drawn onto the canvas is returned. 3 strokeText() This method adds strokes to the text to be drawn on the Canvas element. Print Page Previous Next Advertisements ”;
HTML Canvas – Quick Guide
HTML Canvas – Quick Guide ”; Previous Next HTML Canvas – Introduction 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
HTML Canvas – Basic Animations ”; Previous Next The canvas element completely uses JavaScript to draw shapes and add styles to them. The same JavaScript can be used to make very attractive animations on the Canvas element. Since animations are dynamic, the objects inside the Canvas element take some time to render. Controlling the Animation Canvas element shapes are generally constructed using methods or custom functions. Hence, we cannot add animation to them unless they are rendered correctly on the canvas element. Since animations change the nature of the canvas, scheduled updating must be a compulsory operation. There are some animation methods used to control the functionality of the animations on the Canvas element. Each of the methods is described below S.No Method & Description 1 setInterval(callback_function, time) This method is used to repeat a given task in each timeframe. It takes a function which contains the required task and time in milliseconds as its parameters. 2 setTimeout(callback_function, time) When a task should be done once for a certain period, this method is used. It takes the executable function and time in milliseconds as its parameters. 3 requestAnimationFrame(callback_function) This method updates the browser to perform an animation request before the next animation or update. These animation methods are generally used in the Canvas element to develop 2D games and interactive UI designs. Steps to add basic animations To add animations to the Canvas element, there are some steps to be followed which are listed below Step 1 − Clear the complete Canvas element − To add any animations to the Canvas element, there must be no drawings inside which do not fill the complete canvas space. This can be done by calling the clearRect() method. Step 2 − Save the default Canvas state − Since we apply various styles and add different settings such as transformations, slicing, etc, we have to save the main canvas state to make sure we can roll back to the main state when needed. Save() function is used to achieve this. Step 3 − Draw the shapes with added animations − We render the drawn shapes with different animations available. This is the first step where animations are applied to the Canvas element. Step 4 − Restore the Canvas element when needed − Since we have already saved the canvas states using the save() method, we can restore them before drawing a new frame using the restore() function. Example 1 The following program demonstrates how clearRect() method works and how to use it to perform animations. <!DOCTYPE html> <html lang=”en”> <head> <title>Animations</title> <style> #button { position: absolute; top: 350px; left: 150px; } </style> </head> <body onload=”animation();”> <canvas id=”canvas” width=”600″ height=”400″ style=”border: 1px solid black;”></canvas> <script> function animation() { var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); context.fillStyle = ”purple”; context.fillRect(75, 75, 300, 150); context.font = ”25px Verdana”; context.fillText(”To remove text and rect, press the button”, 10, 300); document.getElementById(”clear”).addEventListener(”click”, function() { context.clearRect(0, 0, canvas.width, canvas.height); }, false); } </script> <div id=”button”> <input type=”button” id=”clear” value=”Clear the whole Canvas element”> </div> </body> </html> Output The output returned by the above program is given below If you press the button, the canvas changes to the image shown below To see the text and shape again, refresh the page. Example 2 The following code shows how simple animations can be performed to the Canvas element. <!DOCTYPE html> <html lang=”en”> <head> <title>Animations</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”animate();”> <canvas id=”canvas” width=”600″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function animate() { window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000); }; })(); function drawShapes(square, context) { context.beginPath(); context.rect(square.x, square.y, square.width, square.height); context.fillStyle = ”green”; context.fill(); context.lineWidth = square.borderWidth; context.strokeStyle = ”black”; context.stroke(); context.closePath(); context.font = ”50px Verdana”; context.fillStyle = ”white”; context.fillText(”Hi”, square.x + 15, square.height + 40); } function animation(square, canvas, context, startTime) { // updating the time and speed of movement parameters var time = (new Date()).getTime() – startTime; var speed = 100; var X = speed * time / 1000; if (X < canvas.width – square.width – square.borderWidth / 2) { square.x = X; } // clearing the Canvas element space context.clearRect(0, 0, canvas.width, canvas.height); drawShapes(square, context); // requesting new frame for animation requestAnimFrame(function() { animation(square, canvas, context, startTime); }); } var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); var square = { x: 0, y: 75, width: 100, height: 100, borderWidth: 3 }; drawShapes(square, context); // buffer time before starting animation setTimeout(function() { var startTime = (new Date()).getTime(); animation(square, canvas, context, startTime); }, 1000); } </script> </body> </html> Output The animated output returned by the above code is After the animation, the position of the square is changed as shown below Example 3 The following code demonstrates a simple looping of TutorialsPoint logo in the Canvas element frame. <!DOCTYPE html> <html lang=”en”> <head> <title>Animations</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”animate()”> <canvas id=”context” width=”350″ height=”120″ style=”border: 1px solid black;background-color: brown;”></canvas> <script> function animate() { var image = new Image(); image.src = ”https://www.tutorialspoint.com/themes/home/tp-diamond-logo-white.png”; var X = 600; var Y = 150; var velocity = 30; var scale = 1.05; var y = -4.5; var disx = 0.75; var imgwidth; var imgheight; var x = 0; var RemoveX; var RemoveY; var context; image.onload = function() { imgwidth = image.width * scale; imgheight = image.height * scale; if (imgwidth > X) { x = X – imgwidth; } if (imgwidth > X) { RemoveX = imgwidth; } else { RemoveX = X; } if (imgheight > Y) { RemoveY = imgheight; } else { RemoveY = Y; } var canvas
HTML Canvas – Images
HTML Canvas – Images ”; Previous Next Images are very important and primary requirement to generate attractive visual content. Canvas API has a wide variety of image manipulation features to take an input image as well as to manipulate them based on the requirement. The interfaces CanvasRenderringContext2D and ImageData contains all the methods and properties to create attractive graphics using images on the Canvas element. Properties Following are the various properties available in HTML5 to deal with images − S.No Property & Description 1 data This data property returns the pixel data of ImageData object. 2 imageSmoothingEnabled This property of the Canvas API determines whether the scaled images available are smoothed or not. It returns true if image is scaled and false if it is not scaled. 3 imageSmoothingQuality This property of the Canvas API lets us to set the quality of the image smoothing for an image drawn on Canvas. Methods The methods available to create graphics based on images inside the Canvas element are given in the below table. S.No Method & Description 1 createImageData() This method can be used to create a new ImageData object with given dimensions. The object formed is filled with black pixels unless changed. 2 drawImage() This method draws the image onto the Canvas element. 3 getImageData() The method getImageData() captures the image frame for the given co-ordinates passed as the parameters. The captured image is printed in the canvas element at given point. 4 ImageData() This constructor method returns newly created Image data object with the data passed as parameters. 5 putImageData() This method paints the data given by ImageData object onto the Canvas element. We can retrieve this data using getImageData() method. Print Page Previous Next Advertisements ”;
HTML Canvas – Path Elements
HTML Canvas – Path Elements ”; Previous Next The path is nothing but forming/drawing a basic shape constructed between two points, it can be defined as a list of points, connected by segments of lines, arcs, curves, etc. that can be used to make different shapes. You can draw a path using the methods provided by the paths2D interface of HTML5 canvas. Path elements Path elements are various basic elements like curves, lines, and arcs used to form a path. Following are the methods provided by HTML5 Canvas API to draw various path elements S.No Method & Description 1 moveTo() We use a virtual pointer while drawing with the path. It is always located at a specified point which can be accessed using the moveTo(x, y) method. 2 ineTo() This method draws a line from the virtual pointer to the point given as parameters in the lineTo() method. Before drawing a line, we must use the moveTo() function to send the cursor to the starting point from which the line should be drawn. 3 arcTo() This method will draw an arc using the path. It takes two points and a radius as parameters. The arc is drawn from start point to end point with the curvature using radius. 4 quadraticCurveTo() This function will draw a curve using one control point which is taken in reference to drawing the curve between the two points. 5 bezierCurveTo() This function will draw a curve between two points using two control points which determines the structure of the curve. Beginning and closing a Path Since there are many functions involved to draw a Path, we use the methods to start and close the path using beginPath() and closePath() respectively. A simple code snippet is shown below on how to use path in the JavaScript code. var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.beginPath(); // ….. path operations context.closePath(); In the above code, the operations which are written in between beginPath() and closePath() functions build the required path. The operations given after closing the path do not affect the path object and do not get executed normally. The moveTo path element One of the most important functions which do not provide any drawing from Canvas but is used to draw any shape from that point is by using the moveTo() function. This method moves the virtual pointer to the coordinates given as their parameters. The method is defined as moveTo(x, y) After initializing the Canvas element by calling beginPath(), we must call the moveTo() function so that the virtual pointer is moved to the given coordinates. At that point, drawing is started and the required shape is constructed. We have to ensure that the moveTo() parameters given are inside the Canvas element. If it is outside the Canvas, the drawing will not be shown and is hidden outside the canvas. Example Following code draws the shape rhombus onto the Canvas element using Path 2D element methods moveTo() and lineTo() <!DOCTYPE html> <html lang=”en”> <head> <title>Rhombus</title> </head> <body onload=”myFun();”> <canvas id=”canvas” width=”555″ height=”555″ style=”border: 1px solid black;”></canvas> <script> function myFun() { var canvas = document.getElementById(”canvas”); if (canvas.getContext) { var ctx = canvas.getContext(”2d”); ctx.beginPath(); ctx.moveTo(300, 100); ctx.lineTo(150, 200); ctx.lineTo(300, 300); ctx.lineTo(450, 200); ctx.lineTo(300, 100); ctx.fillStyle = “blue”; ctx.fill() } } </script> </body> </html> Output The rhombus generated by the above code is The lineTo path element 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. Let us look at an example to see how the method works. Example The following example demonstrates the lineTo() method. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>lineTo()</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”line()”> <canvas id=”canvas” width=”300″ height=”150″ style=”border: 1px solid black;”></canvas> <script> function line() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.lineWidth = 5.0; context.beginPath(); context.strokeStyle = ”black”; context.moveTo(20, 20); context.lineTo(250, 20); context.stroke(); context.beginPath(); context.moveTo(20, 120); context.lineTo(250, 120); context.stroke(); } </script> </body> </html> Output The output formed by the code is The arcTo path element This method draws an arc with the given points and uses the radius, connected to the previous point by a straight line. arc(x, y, radius, startAngle, endAngle, counterclockwise) The arc() method draws an arc that is centered at the point (x, y) with radius given as the third parameter. The arc is starting at startAngle and ends at endAngle going in the direction given as the last parameter. The angles are measured from X-axis. If no direction is given in the last parameter, clockwise is used as default. Angles given in the arc() method are measured in radians only. So, we have to convert degrees to radians before giving input to the method. The last parameter counterclockwise is of Boolean datatype where the arc is drawn clockwise if given false and counterclockwise if given true. When the method arc() is called, just a path is declared and the drawing is done using the call of stroke() or fill(), which draws the arc as per the given path. The quadraticCurveTo path element This method draws a quadratic Bezier curve from the current position to the endpoint given using point(x, y). The curve is drawn with reference to the control point specified by (p1, p2). An example of a quadratic curve is shown below. Example An example to implement quadratic curve is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>quadratic curve</title> <style> body { margin:
HTML Canvas – Colors
HTML Canvas – Colors ”; Previous Next In the previous chapter, we have just focused on drawing shapes on the Canvas using basic styles. In this and the next chapters, we will focus on how to make the shapes and Canvas elements attractive by using various styles. We can perform various operations on the Canvas element and the graphics drawn inside it to make them attractive. The concepts which we use to achieve the required graphics by styles and colors are listed below. Each one of the properties has its own function and uses. We will be learning clearly about each of them in the next pages. Colors Transparency Styles for lines Gradients Patterns Shadows Colors Till now we have seen how to draw shapes on Canvas elements. Now we will be seeing how to add colors to the shapes drawn. The properties available to apply colors to the Canvas element are listed in the below table. S.No Property & Description 1 fillStyle This property is used to fill a color inside the shape. 2 strokeStyle This property is used to color the shape outline. The color property can be assigned in four types Give the name of color directly Eg − ”green”, ”blue” Give color input using hexadecimal values. All the colors are available in the range #000000 to #ffffff. Give the color using RGB values. Eg − rgb(0,5,10). The values of all colors are between rgb(0,0,0) to rgb(255,255,255). Give the color input using RGBA values. Eg − rgba(0,100,200,1) Where r − red component g − green component b − blue component a − opacity value. The value is between 0 and 1 respectively. Example Following example demonstrates fillStyle property on circle and strokeStyle on square. The implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Color</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”color();”> <canvas id=”canvas” width=”400″ height=”250″ style=”border: 1px solid black;”></canvas> <script> function color() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); // fillStyle for circle context.arc(100, 100, 50, 1 * Math.PI, 5 * Math.PI); context.fillStyle = ”green”; context.fill(); // strokeStyle for square context.beginPath(); context.rect(250, 65, 75, 75); context.strokeStyle = ”red”; context.stroke(); context.closePath(); } </script> </body> </html> Output The important thing to remember while using the color properties is that when any property is given, it is applied to the whole shapes in the Canvas. To make the property applicable for only the specified shape, we must use beginPath() and closePath() for the shape. The output for the above code is Transparency Sometimes there is a need for the user to make his graphics transparent. The Canvas is equipped with the translucent property which can be done by using the globalAlpha property or by simply assigning transparency for the Canvas using ”rgba” in the color properties. The property used to make the Canvas element transparent is globalAlpha. The syntax is given below Canvas.globalAlpha = transparency_value The transparency value lies between 0 and 1 where 0 indicates the shape is completely transparent and 1 indicates the shape is opaque. For any shape in the Canvas element, the transparency value is 1 (opaque) by default. Example using globalAlpha The following example takes the same square filled with red color and demonstrates their transparency at different globalAlpha levels. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Transparency</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body onload=”transparency();”> <canvas id=”canvas” width=”500″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function transparency() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); // square with 0.25 transparency context.beginPath(); context.rect(50, 50, 75, 75); context.globalAlpha = 0.25; context.fillStyle = ”red”; context.fill(); context.closePath(); // square with 0.5 transparency context.beginPath(); context.rect(150, 50, 75, 75); context.globalAlpha = 0.5; context.fillStyle = ”red”; context.fill(); context.closePath(); // square with 0.75 transparency context.beginPath(); context.rect(250, 50, 75, 75); context.fillStyle = ”red”; context.fill(); context.closePath(); // square with 1 transparency context.beginPath(); context.rect(350, 50, 75, 75); context.globalAlpha = 1; context.fillStyle = ”red”; context.fill(); context.closePath(); } </script> </body> </html> Output The output for the following code is Example using color properties We use rgba color for the Canvas color properties and demonstrate the color property in the below example. The implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Transparency</title> <style></style> </head> <body onload=”transparency();”> <canvas id=”canvas” width=”500″ height=”200″ style=”border: 1px solid black;”></canvas> <script> function transparency() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.rect(50, 50, 400, 100); context.strokeStyle = ”black”; context.stroke(); context.beginPath(); context.rect(50, 50, 100, 100); context.fillStyle = ”rgba(0,0,255,1)”; context.fill(); context.closePath(); context.beginPath(); context.rect(50, 50, 200, 100); context.fillStyle = ”rgba(0,0,255,0.75)”; context.fill(); context.closePath(); context.beginPath(); context.rect(50, 50, 300, 100); context.fillStyle = ”rgba(0,0,255,0.50)”; context.fill(); context.closePath(); context.beginPath(); context.rect(50, 50, 400, 100); context.fillStyle = ”rgba(0,0,255,0.25)”; context.fill(); context.closePath(); } </script> </body> </html> Output The output for the following code is Rules to fill colors in Canvas We have used the fill() method so many times in previous chapters which does not take any parameters. We can include parameters to the function to make some complex fill shapes. While using fill(), we can optionally provide a specific algorithm to determine the point position and to whether fill it or not. Two types of values can be passed to the function which is given below. nonzero − This is the default rule for the fill function which finds out whether the point or shape lies outside the path or not but fills all the available objects. evenodd −This finds out whether to fill the shape or area available in the path and fills the shape available in an even odd manner. Example
HTML Canvas – Canvas Clock
HTML Canvas – Canvas Clock ”; Previous Next Canvas clock is mostly used to add clock features to the website. Most of the websites available today use the Canvas element to implement time-based applications on their sites as it is very easy to implement, and Canvas can make good client-side animations. We will build a real-time analog clock in this chapter. Let us draw a basic Canvas with a circle in it so that we can make an analog clock using JavaScript. The code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>canvas clock</title> </head> <body onload=”clock();”> <canvas id=”canvas” width=”400″ height=”400″ style=”border: 10px solid black;background-color: burlywood;”></canvas> <script> var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); var radius = canvas.height / 2; context.translate(radius, radius); radius = radius * 0.90; Clock(); function Clock() { context.arc(0, 0, radius, 0, 2 * Math.PI); context.lineWidth = 15; context.strokeStyle = “black”; context.stroke(); context.fillStyle = “#dddddd”; context.fill(); } </script> </body> </html> This returns the body of canvas as Adding a face to Canvas We must draw a canvas first and then draw circle using arc inside the canvas where we can implement the clock. To draw the circle, we have to make sure the center of canvas is the center point of the circle which helps us to make it look better. Following code draws the Canvas element and implements clock face into it. <!DOCTYPE html> <html lang=”en”> <head> <title>canvas clock</title> </head> <body onload=”clock();”> <canvas id=”canvas” width=”400″ height=”400″ style=”border: 10px;”></canvas> <script> var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); var radius = canvas.height / 2; context.translate(radius, radius); radius = radius * 0.90 Clock(); function Clock() { Face(context, radius); } function Face(context, radius) { var gradient; context.beginPath(); context.arc(0, 0, radius, 0, 2 * Math.PI); context.fillStyle = ”white”; context.fill(); gradient = context.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); gradient.addColorStop(0, ”#555555”); gradient.addColorStop(0.5, ”lightblue”); gradient.addColorStop(1, ”#555555”); context.strokeStyle = gradient; context.lineWidth = 25; context.stroke(); context.closePath(); context.beginPath(); context.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); context.fillStyle = ”#555555”; context.fill(); context.closePath() } </script> </body> </html> The output returned by the code is Adding numbers and hands Every clock needs numbers and hands to identify the time. So, we”ll number the clock area symmetrically and draw hands as we commonly see in the real mechanical clock. The implementation code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>canvas clock</title> </head> <body onload=”clock();”> <canvas id=”canvas” width=”400″ height=”400″ style=”border: 10px;”></canvas> <script> var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); var radius = canvas.height / 2; context.translate(radius, radius); radius = radius * 0.90; Clock(); function Clock() { Face(context, radius); Numbers(context, radius); Time(context, radius); } function Face(context, radius) { var gradient; context.beginPath(); context.arc(0, 0, radius, 0, 2 * Math.PI); context.fillStyle = ”white”; context.fill(); gradient = context.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); gradient.addColorStop(0, ”#555555”); gradient.addColorStop(0.5, ”lightblue”); gradient.addColorStop(1, ”#555555”); context.strokeStyle = gradient; context.lineWidth = 20; context.stroke(); context.closePath(); context.beginPath(); context.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); context.fillStyle = ”#555555”; context.fill(); context.closePath() } function Numbers(context, radius) { var angle; var number; context.font = radius * 0.15 + “px Verdana”; context.textBaseline = “middle”; context.textAlign = “center”; for (number = 1; number < 13; number++) { angle = number * Math.PI / 6; context.rotate(angle); context.translate(0, -radius * 0.85); context.rotate(-angle); context.fillText(number.toString(), 0, 0); context.rotate(angle); context.translate(0, radius * 0.85); context.rotate(-angle); } } function Time(context, radius) { var Present_Time = new Date(); var hours = Present_Time.getHours(); var minutes = Present_Time.getMinutes(); var seconds = Present_Time.getSeconds(); hours = hours % 12; hours = (hours * Math.PI / 6) + (minutes * Math.PI / (6 * 60)) + (seconds * Math.PI / (360 * 60)); Hands(context, hours, radius * 0.5, radius * 0.07); minutes = (minutes * Math.PI / 30) + (seconds * Math.PI / (30 * 60)); Hands(context, minutes, radius * 0.8, radius * 0.07); seconds = (seconds * Math.PI / 30); Hands(context, seconds, radius * 0.9, radius * 0.02); } function Hands(context, pos, length, width) { context.beginPath(); context.lineWidth = width; context.lineCap = “round”; context.moveTo(0, 0); context.rotate(pos); context.lineTo(0, -length); context.stroke(); context.rotate(-pos); context.closePath(); } </script> </body> </html> The clock generated after adding numbers and hands by the above code is Starting the clock Till now we have built a functioning analog clock using the Canvas element, but it does not function automatically unless we refresh the HTML page every time. Hence, we will be adding another function to make the clock autonomous so we can use it to identify the time without any error. This makes the clock automated and works without any update of time. The code for the implementation is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>canvas clock</title> </head> <body onload=”clock();”> <canvas id=”canvas” width=”400″ height=”400″ style=”border: 10px;”></canvas> <script> var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); var radius = canvas.height / 2; context.translate(radius, radius); radius = radius * 0.90; setInterval(Clock, 1000); function Clock() { Face(context, radius); Numbers(context, radius); Time(context, radius); } function Face(context, radius) { var gradient; context.beginPath(); context.arc(0, 0, radius, 0, 2 * Math.PI); context.fillStyle = ”white”; context.fill(); gradient = context.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); gradient.addColorStop(0, ”#555555”); gradient.addColorStop(0.5, ”lightblue”); gradient.addColorStop(1, ”#555555”); context.strokeStyle = gradient; context.lineWidth = 20; context.stroke(); context.closePath(); context.beginPath(); context.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); context.fillStyle = ”#555555”; context.fill(); context.closePath() } function Numbers(context, radius) { var angle; var number; context.font = radius * 0.15 + “px Verdana”; context.textBaseline = “middle”; context.textAlign = “center”; for (number = 1; number < 13; number++) { angle = number * Math.PI / 6; context.rotate(angle); context.translate(0, -radius * 0.85); context.rotate(-angle); context.fillText(number.toString(), 0, 0); context.rotate(angle); context.translate(0, radius * 0.85); context.rotate(-angle); } } function Time(context, radius) { var Present_Time = new Date(); var hours = Present_Time.getHours(); var minutes = Present_Time.getMinutes(); var seconds = Present_Time.getSeconds(); hours = hours % 12; hours = (hours * Math.PI / 6) + (minutes * Math.PI / (6 * 60))
Composting and Clipping
HTML Canvas – Composting and Clipping ”; Previous Next We generally draw shapes on each other in the Canvas element when there is a need to draw more than one shape. We can use globalCompositeOperation property to order the composite shapes and there is another property clip which helps us to hide the non-required parts from the constructed shapes. The properties are mentioned below globalCompositeOperation − By using this property, we can mask off existing shapes, draw new shapes on the existing ones, and clear sections. The values accepted by this property are mentioned in the below table. Source-over Source-in Source-out Source-atop destination-over destination-in destination-out destination-atop lighter copy xor multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hue saturation color luminosity Example The following example implements the composting properties. The 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> Composting </title> </head> <body onload=”composting();”> <canvas id=”canvas” width=”400″ height=”250″ style=”border: 1px solid black;”></canvas> <script> function composting() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.fillStyle = ”blue”; context.fillRect(25, 25, 200, 200); context.fill(); context.globalCompositeOperation = ”darken”; context.fillStyle = ”purple”; context.fillRect(125, 25, 200, 200); context.fill(); context.fillStyle = ”yellow”; context.fillRect(225, 25, 100, 200); context.fill(); } </script> </body> </html> Output The output returned by the above code is Clipping is similar to building shapes in canvas element using paths but it acts like a mask that removes unwanted parts of the obtained shape. The method used to achieve clipping is given below Clip() − This method turns the built path shape into a clipping path. It is generally used instead of the closePath() function which turns it into a clipping path rather than stroking or filling the path. Example for clipping The following code implements the clipping method for the canvas element. <!DOCTYPE html> <html lang=”en”> <head> <title> Clipping </title> </head> <body onload=”clipping();”> <canvas id=”canvas” width=”400″ height=”250″ style=”border: 1px solid black;”></canvas> <script> function clipping() { var canvas = document.getElementById(”canvas”); var context = canvas.getContext(”2d”); context.fillStyle = ”skyblue”; context.fillRect(0, 0, 400, 250); context.fill(); context.beginPath(); context.arc(200, 125, 100, 1 * Math.PI, 5 * Math.PI); context.fillStyle = ”orange”; context.fill(); context.clip(); } </script> </body> </html> Output The output for the above code formed is shown below − Print Page Previous Next Advertisements ”;