ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Web Tutorial Series: HTML 5 The Canvas Element (Part II): Colors, Shadows, Shapes, & Images

Updated on April 2, 2014

Review of Our Last Tutorial & Our Goals

In our last tutorial, A Web Tutorial Series: HTML 5 - The canvas Element, A HTML Container for Graphics, we introduced the HTML canvas element which was added in the HTML 5 release to give developers a means of adding images, shapes, and text techniques to their web pages. We drew some simple shapes and worked with outline and color filled text. In this tutorial we will look at some more involved properties associated with that element in terms of styling text, drawing more involved shapes, and using images. We willbe using JavaScript, but not embedding it in the HTML code, but using it as linked in files.

One of the Thing You Might Want to Place on A Canvas: An Image

An image is something you might want to place on a canvas. The following snapshot show part of an image which was larger than the canvas size. It is a way to crop a photo for your page, if the pages has a space limitation and you happen to be more interested in part of the image detail than having to present the entire image.

The code producing this image illustrates several concepts with respect to JavaScript which we will defer in this tutorial and cover in the next tutorial when we talk more about JavaScript functions in HTML.

Incorporating an Image on a Canvas

The image and the code required to display it in the canvas.
The image and the code required to display it in the canvas.

Placing Text On A Canvas

Several important concepts are illustrated in this example. For that reason the code is included here.

In the HTML file there are two main points to emphasize:

  • in the head element we are not including the JavaScript code, rather we make a reference to a file. Note in this case we merely specify the file name as the code is contained in the same directory as the HTML file. Generally, in development environments this would not be the case and an absolute path or relative path name would be required.

<head>
<script src="drawing_text.js"></script>

.....anything else you might like to specify goes here. <title> is generally inserted

</head>

  • we specifed the required id for the canvas. The id is need by the JavaScript code to locate the canvas. The required attributes with and height are here as well. (The section tags were add to illustate some past learning regarding semantic tags in HTML.)

<section id="main">
<canvas id="canvas" width="500" height="300"
style="border:5px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</section>
</body>
</html>

  • This JavaScript function is what performs the write (i.e. canvas.fillText). We introduced two canvas properties: font and textAlign. "font" can contain any of the usual attributes we have seen with text styling in HTML. We will discuss the statement canvas.textAlign in the next section.

function drawingText() {
var c = document.getElementById('canvas');
canvas = c.getContext('2d');

canvas.font = "bold 25px Arial";
canvas.textAlign = "start";
canvas.fillText("When in the course of Human events...",10,30);

}

  • This final statement regarding the need for event listeners when using the canvas element will be discussed in the next tutorial.

window.addEventListener("load",drawingText, false);

Writing Text on a Canvas Using JavaScript

This is the HTML file assicated with the written canvas text illustrated in the next snapshot. Notice that we used a reference to the JavaScript code in the head rather than placing  it inline  in the HTML file.
This is the HTML file assicated with the written canvas text illustrated in the next snapshot. Notice that we used a reference to the JavaScript code in the head rather than placing it inline in the HTML file.
This illustration shows the placement of the text on the canvas. Note the use of the canvas properties font and textAlign.
This illustration shows the placement of the text on the canvas. Note the use of the canvas properties font and textAlign.

The Canvas textAlign Property

The textAlign property looks a little different from what we encountered in HTML. The illustration which follows discuss the possible values for textAlign. A code snippet is also provided there. All of the alignment performed is relative to the blue line which was drawn. The blue line was just drawn to give a reference point the what values were set for x and y in each of the case.

The Various Properties of Text Alignment on a Canvas

This snapshot show the use of the canvas textAlign property. The values being: right,  left, start, end , and center.
This snapshot show the use of the canvas textAlign property. The values being: right, left, start, end , and center.

Drawing a Shadow for Text

A nice effect which can make a reader of your web page take real notice (if not overdone) is a shadow effect. In creating a shadow for one important point is that the statements relating to the shadow must precede the drawing of the text.

The statements involved with creating shadows are property statements of the canvas. Examples are:

canvas.OffsetShadowX= { a value in pixels}; which creates the shadow that number of px to the right of the text.

canvas.OffsetShadowY = {a value in pixels}; which creates the shadow that number of px down from the text.

Two other properties for shadows are;

canvas.shadowColor = {any valid color}. The color value can be specified as a name. an rgb value, an rgba value, or a hex value. Note that all color specifications must be enclosed with quotes.

canvas.shadowBlur = { a value from 0 (no blur) on upwards} indicates the indistinctness of the shadow.

Creating a Shadow For Text

In this illustration there are four actions performed on the text to create a shadow: shadowOffsetX, shadowOffsetY, shadowColor, and shadowBlur.
In this illustration there are four actions performed on the text to create a shadow: shadowOffsetX, shadowOffsetY, shadowColor, and shadowBlur.

Drawing Shapes

The following illustration demonstrates drawing a simple figure on a canvas. The statements used for this triangle include: the beginPath() method. Which creates an alert to JavaScript that a drawing is about to take place. We then use the moveTo() method to go to the point at which the drawing will start. Next we used the lineTo() method to create a line, a second line was drawn with the lineTo() method, we followed that with the closePath() method to draw the segment which draws from the current point to the origination, completing the figure. Now we need to call the stroke() method to actually complete the figure.

We used the simple lineTo() method in our example. There are other methods to connect two points:

  • arc() - the values specified are x, y, radius, beginning angle, ending angle, and direction (clockwise or counterclockwise)
  • arcTo() - creates an between two tangents. A simple example would be creating a "rounded corner".
  • bezierCurveTo()
  • quadricCurveTo()

,

Please Rate This Tutorial on Its Content and Clarity

Cast your vote for Did this tutorial meet your expectations?

Wrap Up and What's Next

In this tutorial we first looked at placing an image on a canvas. Care mustbe taken to size the canvas appropriately to the image size. Next we looked at writing text to a canvas and using some shadowing and burring techniques.We ended this tutorial by demonstrating how to draw a simple figure on a canvas.

We used JavaScript outside of the HTML file. We created a script file (and the file type should be specified as "js"). and linked the file in in the header.

In the next tutorial we will finish up out work with the canvas element. We will also point out certain features of the JavaScript code we implemented.

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://corp.maven.io/privacy-policy

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)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)