Wrapping Your Head Around Canvas: Part 1

HTML5 is no longer a ‘way of the future ‘ as it is more common place now that most of us, if not all of us, are starting to implement it into the things we create.

One of the newest features that have most of you cooing, aside from the new video and audio tags, is Canvas. It has been dubbed a convenient replacement for the use of flash in the browser, and it translates well across multiple devices.

The name of the HTML tag sums up the basis of its implementation. Canvas provides a 2D drawing API for images, text, lines, shapes, and so on. At times it brings back memories of using MS Paint; I know I’m not alone in this sentiment when I see websites like canvaspaint.org.

The fact of the matter is when you dig down into it, you can do so much more with Canvas, and it could possibly be one of the biggest improvements to HTML.

You’re only truly limited by your understanding of the API and imagination. What you’ll be able to do at the end of this series will be up to you, but I hope that if this canvas series doesn’t help you most of everything about HMTL5 Canvas it will at least provide a springboard for you to dive deep into the API.

Let’s Begin with the Basics

Browser Support

One of the biggest questions facing us is of course browser support. Most browsers have been working on creating more modern versions to keep up with all of the new elements that HTML5 and CSS3 have introduced. Now even IE9 supports most if not all of the new technologies that drive these languages. Unfortunately for those of you that are stuck with using versions of IE like 6, 7, and 8, JavaScript may be more help in those situations. As a matter of fact, there is a JavaScript compatibility fix for IE8 called The ExplorerCanvas project. All you have to do is include the extra JS file before any of the canvas tags in your page. You can exclude this snazzy little piece of JS from the other browsers that already render Canvas by using conditional comments.

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

Getting Started with Canvas

You would execute canvas as you would any other new HTML tag by using the <canvas> tag. The basic working size is 300px by 150px and will show up empty or invisible. It’s a good idea to put in some fallback content in case the browser does not support canvas.

Think of canvas like your new drawing pad and now that it is setup, we can begin to draw in that space. Keep in mind that when you are using canvas, you are not drawing on the canvas element itself, but instead you are drawing on the 2d context in which it renders. This would be where JavaScript API comes into play. You’ll find your canvas element by using getElementByID and then you can initialize the context that you would like. Remember to place your <script> tags either before or after, like so:

Congratulations! You just finished writing you first bit of canvas equivalent to the ‘hello world’ statement.

With that achievement notched in your HTML5 dev belt let’s take a closer look into the 2D API. Creating basic lines and shapes is what lies at the core of canvas, as you saw in the previous code above. Using the fillStyle or strokeStyle you can render the colors and strokes of the shapes more easily. When approaching the color values, keep in mind that they are the same as the CSS values rgb(), rgba(), and hsla().

So to draw a basic solid rectangle we would use fillRect, and use strokeRect to create the same rectangle with only borders. Easy right? I mean so far this all seems to be pretty straight forward. now let me introduce you to clearRect. You can implement this property to clear a portion of your drawn rectangle. Using the X, Y, width, and height properties can and will be used in all three of these methods below, you can even change your line thickness. Let’s take a look:

Paths

Creating paths is just as simple as creating basic shapes. Paths allow you to create custom shapes, the catch 22 is that you have to create the outlines, then you can add strokes, and finally add the fill. To get started with your custom shape you will use beginPath. The code isn’t too complicated to understand let’s draw a circle:

The resulting product gives you a filled circle at the x, y coordinates of 75, 75, with a radius of 50. The next arguments in our line of code are the start and end points in radians. In the above example, we wanted to create a complete circle, so we started with 0 and ended at Math.PI*2 which is equal to 360 degrees. The last argument tells in what direction to draw the circle, in this instance we opted for clockwise so our statement is ‘true’ You can add a bit of color to the circle now using fillStyle:

Now that your head is full of all sorts of fun with creating arcs, it’s time to move forward and explore something a tad more complex, like creating Bezier curves. With methods like bezierCurveTo and quadraticCurveTo you can create multiple curves and paths that have a radius that aren’t central the curve. By using control points we can define where and how to draw the curves. If you are looking to create a curve with multiple points, then the bezierCurveTo may be just the thing as opposed to the quadraticCurveTo that only has one control point.

Let’s take a closer look at the quadraticCurveTo method, more specifically the arguments that it calls. The first is the ‘x’ position of our control point, next there is the y position of the same point, then the x coordinate of the end of our path, and finally the y coordinate of the end of our path.

The bezierCurveTo method isn’t too different other than the fact that you now are calling out 2 control points:

ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);

Conclusion

Voila Folks!

You now know how to setup and begin working in Canvas. This isn’t to say that I expect you to take what you’ve learned here to inspire the next great idea in canvas, but at least you are beginning to build a solid foundation of understanding the technology.

We’ll dive into more about the features and what Canvas can do in my next article, so keep an eye out for part 2 of ‘Wrapping Your Head Around Canvas’.

Josh is currently the Creative Director at Rappsody Studios located in Jacksonville, FL and has been working in across the web for close to eight years. He has a soft spot for front-end development and comics.
More articles by Joshua Rapp

Picking up from where we left off, we need to start by creating some HTML to display the data we’ve stored in the $results variable. You can always modify this to suite your project. I’ll be using a table structure. <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <link href="styles/theme.css" rel="stylesheet"/> <title>PHP & MySQL</title>\ </head> <body> <div id="wrapper"> <table> <thead> <th>Title</th>...

In the first two parts of this series, we created the data layer that will hold the polling data and established methods for setting the variable values and reading from the database tables. In this part, we will build the methods that will write new polls and answers to the tables. The addPoll method adds a new record to the devdrive_polls table and returns a Boolean value that signals if the record was added successfully. function addPoll($aArgs) { // add a poll record $sql = "LOCK TABLES devdrive_polls...

A SQL injection is a common programming error the consequences of which can be really devastating. Many successful hacking attacks start when a hacker discovers a vulnerability that gives an opportunity to inject SQL code. When an SQL injection occurs, the structure of an SQL query is compromised and as a result you are left at the mercy of the potential hackers. If there is a vulnerability found, hackers can exploit it to gain access not only to your site and database but in extreme cases also to your corporate...

So far we've created some basic PHP pages and added some simple authentication. Today we're going to going to build on that by adding database support. This will allow us to add proper authentication to our application and start saving tasks. I should also note that I am currently writing PHP in-line and not using functions (or object orientated PHP) I will tidy this up in the next tutorial and spend more time explaining it and what it's benefits are. Last week ... Last week we installed XAMPP, so you should...

In our last session, we looked at the process of entering information on ad banners and ad clients, as well as generating ad activity reports. This week, we examine how to retrieve a random banner ad. We will also learn how to delete, activate and deactivate ads and clients. The getRandomAd() function retrieves a random ad by using the PHP rand() function. The function returns the ad’s primary key ID, client ID, title, URL and redirect path. The function also updates the activity table for this banner...

In our last PHP Ad Tracker lesson, we constructed the database tables for our ad banner application. Now we are ready to construct the data object that will hold the variables and functions that will display, add, edit and delete the data in those tables. Once we name all of the variables and functions, we will start applying the code to them. Variables: The data object class will hold two variables: one to hold the banner ad ID number from the ads table, and one to hold the database connection information....

In the previous lesson, we examined the basic functions of our banner ad tracking system, including the retrieval of records for both banner ads and advertisers. In this lesson, we will look at the functions responsible for generating reports and manipulating the data in the ads table and advertiser table. The getClientsList() function retrieves active client records and sorts them alphabetically by client name: function getClientsList() { // get clients from db $sql = "SELECT ad_client_id,...

Introduction ... I’m going to tell you a story, its about love, death and re-birth... Or something In the beginning there was a young html element called <table>. He had one purpose in life, to display data and life was good. But before long though he had been corrupted, his masters used him to define layout and structure. Things he was not originally designed to do, and so began the dark ages of web design. Then one day, there came a young knight called CSS, and with him he brought light to designers...

About

DeveloperDrive.com is a blog about web development from the makers of the popular web design blog WebdesignerDepot.com
Founded in 2011, we focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.