HTML Canvas – First Application ”; Previous Next In the previous chapters we have already seen how to create a Canvas element using the <canvas> tag. Now we will style the Canvas element using simple CSS styles which helps us to understand how the Canvas element is formed. Let us first create an empty Canvas element and style using the following attributes Add background-color Change border Adding background color to the Canvas element Following code demonstrates how to add color to the Canvas element using CSS style attributes. We are using background_color attribute of the Canvas element. The code is given below. <!DOCTYPE html> <html lang=”en”> <head> <title>Canvas Element</title> <style> #canvas{ border:5px solid black; background-color: green; } </style> </head> <body> <canvas id=”canvas” width=”300″ height=”150″ > This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled. </canvas> </body> </html> Output Changing border of the Canvas element By using CSS style attributes, we can change the border style of Canvas element easily. It is useful when creating an interactive visual graphics using Canvas. Following is the implementation of changing the border style of the Canvas element. <!DOCTYPE html> <html lang=”en”> <head> <title>Canvas Element</title> <style> #canvas{ border:2px dotted black; } </style> </head> <body> <canvas id=”canvas” width=”300″ height=”150″ > This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled. </canvas> </body> </html> Output Instead of using solid while creating the Canvas element, we can use one of the following to change the style of the Canvas border per our requirement Dotted Dashed Double Groove Ridge Print Page Previous Next Advertisements ”;
Search Results for: html_canvas
HTML Canvas – Home
HTML Canvas Tutorial PDF Version Video Courses Quick Guide Resources Job Search 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. Audience This tutorial has been created for the beginners to help them understand the basics of Canvas element. After completing this tutorial, you will find yourself at a moderate level of expertise in Canvas API, from where you can take yourself to the next levels. You will be able to generate various graphic designs useful for creating virtual content, making web-pages interactive and much more. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Webpages and its programming languages such as HTML, CSS, and JavaScript. Although it is a beginner”s tutorial, we assume that the readers have a good exposure to any front-end programming environment and knowledge of basic concepts such as tags, attributes, and elements. We strongly recommend that you gain some basic knowledge of HTML and JavaScript before proceeding to learn Canvas element. Print Page Previous Next Advertisements ”;
HTML5 – Geolocation
HTML – Geolocation API ”; Previous Next HTML Geolocation API used by web applications to access geographical location of user. Most of the modern browsers and mobile devices support Geolocation API. JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. Syntax var geolocation = navigator.geolocation; The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device. Geolocation Methods The geolocation object provides the following methods: Method Description getCurrentPosition() This method retrieves the current geographic location of the user. watchPosition() This method retrieves periodic updates about the current geographic location of the device. clearWatch() This method cancels an ongoing watchPosition call. Following is a sample code to use any of the above methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler); watchId = geolocation.watchPosition(showLocation, errorHandler, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }); navigator.geolocation.clearWatch(watchId); } Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any. Location Properties Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information. The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null. Property Type Description coords objects Specifies the geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. coords.latitude Number Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00]. coords.longitude Number Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00]. coords.altitude Number [Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid. coords.accuracy Number [Optional] Specifies the accuracy of the latitude and longitude estimates in meters. coords.altitudeAccuracy Number [Optional] Specifies the accuracy of the altitude estimate in meters. coords.heading Number [Optional] Specifies the device”s current direction of movement in degrees counting clockwise relative to true north. coords.speed Number [Optional] Specifies the device”s current ground speed in meters per second. timestamp date Specifies the time when the location information was retrieved and the Position object created. Following is a sample code which makes use of position object. Here showLocation method is a callback method: function showLocation( position ) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; … } Handling Errors Geolocation is complicated, and it is very much required to catch any error and handle it gracefully. The geolocation methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties: Property Type Description code Number Contains a numeric code for the error. message String Contains a human-readable description of the error. The following table describes the possible error codes returned in the PositionError object. Code Constant Description 0 UNKNOWN_ERROR The method failed to retrieve the location of the device due to an unknown error. 1 PERMISSION_DENIED The method failed to retrieve the location of the device because the application does not have permission to use the Location Service. 2 POSITION_UNAVAILABLE The location of the device could not be determined. 3 TIMEOUT The method was unable to retrieve the location information within the specified maximum timeout interval. Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method: function errorHandler( err ) { if (err.code == 1) { // access is denied } … } Position Options Following is the actual syntax of getCurrentPosition() method: getCurrentPosition(callback, ErrorCallback, options) Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device. Following are the options which can be specified as third argument: Property Type Description enableHighAccuracy Boolean Specifies whether the widget wants to receive the most accurate location estimate possible. By default this is false. timeout Number The timeout property is the number of milliseconds your web application is willing to wait for a position. maximumAge Number Specifies the expiry time in milliseconds for cached location information. Following is a sample code which shows how to use above mentioned methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler, {maximumAge: 75000}); } Examples of HTML Geolocation API Here are some examples that shows how to access geolocation in HTML. Get Current Location The following code shows how to access current location of your device using JavaScript and
HTML5 – Geo-Location
HTML – Geolocation API ”; Previous Next HTML Geolocation API used by web applications to access geographical location of user. Most of the modern browsers and mobile devices support Geolocation API. JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. Syntax var geolocation = navigator.geolocation; The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device. Geolocation Methods The geolocation object provides the following methods: Method Description getCurrentPosition() This method retrieves the current geographic location of the user. watchPosition() This method retrieves periodic updates about the current geographic location of the device. clearWatch() This method cancels an ongoing watchPosition call. Following is a sample code to use any of the above methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler); watchId = geolocation.watchPosition(showLocation, errorHandler, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }); navigator.geolocation.clearWatch(watchId); } Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any. Location Properties Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information. The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null. Property Type Description coords objects Specifies the geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. coords.latitude Number Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00]. coords.longitude Number Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00]. coords.altitude Number [Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid. coords.accuracy Number [Optional] Specifies the accuracy of the latitude and longitude estimates in meters. coords.altitudeAccuracy Number [Optional] Specifies the accuracy of the altitude estimate in meters. coords.heading Number [Optional] Specifies the device”s current direction of movement in degrees counting clockwise relative to true north. coords.speed Number [Optional] Specifies the device”s current ground speed in meters per second. timestamp date Specifies the time when the location information was retrieved and the Position object created. Following is a sample code which makes use of position object. Here showLocation method is a callback method: function showLocation( position ) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; … } Handling Errors Geolocation is complicated, and it is very much required to catch any error and handle it gracefully. The geolocation methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties: Property Type Description code Number Contains a numeric code for the error. message String Contains a human-readable description of the error. The following table describes the possible error codes returned in the PositionError object. Code Constant Description 0 UNKNOWN_ERROR The method failed to retrieve the location of the device due to an unknown error. 1 PERMISSION_DENIED The method failed to retrieve the location of the device because the application does not have permission to use the Location Service. 2 POSITION_UNAVAILABLE The location of the device could not be determined. 3 TIMEOUT The method was unable to retrieve the location information within the specified maximum timeout interval. Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method: function errorHandler( err ) { if (err.code == 1) { // access is denied } … } Position Options Following is the actual syntax of getCurrentPosition() method: getCurrentPosition(callback, ErrorCallback, options) Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device. Following are the options which can be specified as third argument: Property Type Description enableHighAccuracy Boolean Specifies whether the widget wants to receive the most accurate location estimate possible. By default this is false. timeout Number The timeout property is the number of milliseconds your web application is willing to wait for a position. maximumAge Number Specifies the expiry time in milliseconds for cached location information. Following is a sample code which shows how to use above mentioned methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler, {maximumAge: 75000}); } Examples of HTML Geolocation API Here are some examples that shows how to access geolocation in HTML. Get Current Location The following code shows how to access current location of your device using JavaScript and
HTML5 – SVG
HTML – SVG ”; Previous Next HTML SVG (Scalable Vector Graphics) is used to define vector graphics in XML that can be embedded into HTML pages. SVG is different from normal images as it does not lose quality even after zooming it. XML is an abbreviation that stands for Extensible Markup Language and it is a data description language. It does not have any predefined tags hence; the users are required to define their own tags depending on the need. What is SVG? SVG stands for Scalable Vector Graphics. SVG helps us to draw any types of images using XML coding. Zooming a XML vector does not lose it”s quality It is mostly useful for vector-type diagrams like Pie charts, and two-dimensional graphs in an X, Y coordinate system. SVG became a W3C Recommendation on 14 January 2003. SVG (Scalable Vector Graphics) The PNG, GIF, and JPG files are bitmap graphics and SVG files are vector graphics. The main difference between these two is that bitmap graphics are made up of a grid of tiny pixels but, vector graphics are defined by coding hence vector graphics does not lose quality after zooming. Ways to use SVG in HTML? There are two ways of embedding the SVG files in HTML Using <img> tag Using <svg> tag Using <img> tag We can directly embed the SVG files inside our web page using the src attribute of <img> tag as shown below. We can pass either the path or an online link to the svg image. <img src = “yourfilename.svg”/> Using <svg> tag HTML allows embedding SVG directly using <svg>…</svg> tag which has the following syntax <svg> <!– code to create graphics –> </svg> Tags inside SVG Element There are some predefined SVG elements that are used to draw various shapes like circles, rectangles, lines and so on. They are as follows Tags Description <rect> Used to define a rectangle in vector graphics for given width and height as attribute. <circle> Used to define circle for given coordinates of top-left corner and radius as attribute. <ellipse> Used to define ellipse for given coordinates of top-left corner, length of major axis and length of minor axis as attribute. <line> Used to draw line for for given two coordinates as attribute <polyline> Used to define a polyline for given coordinates of series of connected points <polygon> Used to define a polygon for given coordinates that joins in straight line. The <svg> tag is the top level (root) element of the above mentioned tags. They are defined inside the svg element. Attributes of SVG Elements The following table contains a list of attributes of SVG Elements Attribute Description X The top-left x-axis coordinate. Y The top-left y-axis coordinate. width The width of rectangle figure. height The height of rectangle figure. rx The x-axis” roundness of ellipse. ry The y-axis” roundness of ellipse. style Indicate an inline style. Examples of HTML SVG Element Following are some examples that shows how to draw different graphical elements using SVG tag. Draw a Circle using HTML SVG Tag Following is the SVG example which would draw a circle using <circle> tag inside SVG element. Here cx is x coordinate of top-left corner of circle, cy is y coordinate of top-right corner of circle <!DOCTYPE html> <html> <head> <title>SVG-Circle</title> </head> <body> <h2>HTML SVG Circle</h2> <svg height=”500″ > <circle cx=”50″ cy=”50″ r=”50″ fill=”red” /> </svg> </body> </html> Draw a rectangle using HTML SVG Tag Following is the SVG example which would draw a rectangle using <rect> tag. We use height and width attributes to make a rectangle <!DOCTYPE html> <html> <head> <title>SVG Rectangle</title> </head> <body> <h2>HTML SVG Rectangle</h2> <svg height = “200”> <rect width = “300” height = “100” fill = “red” /> </svg> </body> </html> Draw a line using HTML SVG Tag Following is the SVG example which would draw a line using <line> tag for provided coordinates of two points(x1,y1, x2,y2). We can also use the style attribute which allows us to set additional style information like stroke and fill colors, width of the stroke, etc. <!DOCTYPE html> <html> <head> <title>SVG Line</title> </head> <body> <h2>HTML SVG Line</h2> <svg height=”200″> <line x1=”0″ y1=”0″ x2=”200″ y2=”100″ style=”stroke:red;stroke-width:2″/> </svg> </body> </html> Draw a Ellipse using HTML SVG Tag Following is the SVG example which would draw an ellipse using <ellipse> tag. Here cx and cy are coordinates of top-left corner of ellipse, rx is radius along x axis and ry is radius along y axis. <!DOCTYPE html> <html> <head> <title>SVG Ellipse</title> </head> <body> <h2>HTML SVG Ellipse</h2> <svg height=”200″> <ellipse cx=”100″ cy=”50″ rx=”100″ ry=”50″ fill=”red” /> </svg> </body> </html> Draw a Polygon using HTML SVG Tag Following is the SVG example which would draw a polygon using <polygon> tag. The points attribute defines the vertices of the polygon. Each pair of coordinates (x, y) specifies a vertex, and the polygon is drawn by connecting these vertices with straight lines. <!DOCTYPE html> <html> <head> <title>SVG</title> </head> <body> <h2>HTML SVG Polygon</h2> <svg height=”200″> <polygon points=”20,10, 300,20, 170,50, 130,70″ fill=”red” /> </svg>