ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Web Tutorial Series: HTML 5 - The canvas Element, A HTML Container for Graphics

Updated on March 31, 2014

Using Techniques in This Canvas Tutorial

Using techniques in this tutorial can result in some interesting visuals that can be incorporated into backgrounds and borders.
Using techniques in this tutorial can result in some interesting visuals that can be incorporated into backgrounds and borders.

The <canvas> Element

The <canvas> element by default has no border nor any content. Since multiple canvas elements can occur on a page and since a drawing script needs to refer to the canvas an id attribute is necessary. Also, width and height attributes are needed. The basic canvas declaration would look something like:

<canvas id=my_canvas width=200px height=200px>.

Illustration of Our First Canvas Example

In our first canvas example we illustrate a "barebones" outline : the usual elements for a HTML page (.e.g. body), element for the Java Script ( e.g. ), a canvas element definition, and the statements which perform some drawing action.
In our first canvas example we illustrate a "barebones" outline : the usual elements for a HTML page (.e.g. body), element for the Java Script ( e.g. ), a canvas element definition, and the statements which perform some drawing action.

Dissecting Our First Canvas Example

Let's dissect our first example.(The code is illustrated in the snapshot above.) The canvas is defined in the statement:

<canvas id="myCanvas" width="200" height="200"

style="border:5px solid #d3d3d3;

margin:100px 100px;">

Your browser does not support the HTML5 canvas tag.</canvas>

Margin and border can specified as usual in the CSS styling of the canvas element. Styling attributes are not a requirement of the canvas element.

However, the id attribute is a requirement. The id attribute is used to relate this canvas uniquely with the JavaScript code which follows. JavaScript is the "workhorse" of the canvas element. JavaScript performs the drawing.

The height and width attributes are normal canvas attributes. They are required because they define the size of the canvas. The canvas couldn't exist without a size specification.

Notice the text which precedes the closing canvas tag. This statement is placed there since not all browser (particularly older browsers) have support for the canvas element. In that case this statement would be displayed.

Next, we have the JavaScript <script> block:

<script>

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

ctx.fillStyle="#0000FF";

ctx.fillRect(0,0,100, 80);

</script>

The first statement locates the canvas element, my canvas by invoking the method on the document object.

The getContext("2d") method returns a built-in HTML5 object with many properties and methods for drawing paths, boxes, circles, text, images, and more.

The fillStyle property can be any valid color, a gradient, or pattern. The default fillStyle is #000000 (black).

The fillRect(x,y,width,height) method draws a rectangle filled with the current fill style. In our case we specified #0000FF (blue). Any valid color function (e.g. rdg, rgba) or specification (e.g. "green", "pink") can be used.

Canvas Coordinates

The canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinate (0,0) So, the fillRect() method above which had the parameters (0,0,100,80) canbe described as follows:

Starting at the upper-left corner (0,0) and going to the location 100 pixels on the x axis and 80 pixels on the y axis, paint the rectangle with the specified color.

That painting action completes the script and terminates the loading of the page elements.



Drawing a Line on a Canvas

To draw straight lines on a canvas, we will use the following two methods:

  • moveTo(x,y) defines the starting point of the line

  • lineTo(x,y) defines the ending point of the line

To actually draw the line, we must use one of the "ink" methods, like stroke().

The snapshot illustrates this technique.

A Line Drawing Example

Not very exciting but it demonstrates the fundamentals: move, lineTo stroke.
Not very exciting but it demonstrates the fundamentals: move, lineTo stroke.

Drawing A Circle

To draw a circle on a canvas, we will use the following method:

  • arc(x,y,r,start,stop)

To actually draw the circle, we must use one of the "ink" methods, like stroke() or fill(). Not in this example, in the snapshot below, we use "fill".

Illustration of Drawing a Circle

Notice that our definition of the circle uses the Math.pi (value of pi) in the arithmetic term 2* Math.pi (2 times the value of pi, 3.1415926...)
Notice that our definition of the circle uses the Math.pi (value of pi) in the arithmetic term 2* Math.pi (2 times the value of pi, 3.1415926...)

Writing Text on a Canvas: Filled Text and Outline Text

The properties and methods for drawing text on a canvas are:

  • font - defines the font properties for text

  • fillText(text,x,y) - Draws "filled" text on the canvas as with normal text. The default color is black. If another color is desired then you must precede this statement with the fillStyle property of the 2d context.

  • strokeText(text,x,y) - Draws text on the canvas (no fill). Instead you see the letter outline.


Illustration of Filled Text and Outline Text

Notice we have written two text string to the canvas: one with fillText() and the second with strokeText() as the methods.If the color "green" (#00ff00) had not been assigned the default fillStyle() would be black (#000000).
Notice we have written two text string to the canvas: one with fillText() and the second with strokeText() as the methods.If the color "green" (#00ff00) had not been assigned the default fillStyle() would be black (#000000).

Drawing Canvas Gradients

Canvas gradients can be used to fill rectangles, circles, lines, text, and other shapes. Canvas are not limited to solid colors.

There are two different types of gradients:

  • createLinearGradient(x,y,x1,y1) - Creates a linear gradient

  • createRadialGradient(x,y,r,x1,y1,r1) - Creates a radial/circular gradient

Once we have decided on and created a gradient object, we must add two or more color stops to use multiple colors.

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

Set the fillStyle or strokeStyle property to the gradient, and then draw the shape.

The following illustrations show a two color gradient and a three color gradient example.

A Two Color Gradient

The first color specified is blue. The second specification is for green. The values allowed for the color stop are between zero and one.
The first color specified is blue. The second specification is for green. The values allowed for the color stop are between zero and one.
A three color gradient. Note the decimal values for the color stop.
A three color gradient. Note the decimal values for the color stop.

Wrap Up and What's Next

The canvas element allows for a number of attractive (and not so attractive) additions of color to a web page. We have investigated some of the simple uses in this tutorial. In the following tutorial, Part II, we complete our look at simple gradients with thee radial gradient. and take a more serious look at color enhancing effects for text which are perhaps more useful than what was demonstrated here. We also will take note of one necessary concern when loading large images on a web page as well.

Rate This Tutorial on its Content

Cast your vote for Was this tutorila easy to follow?

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)