Home Wrapping Your Head Around Canvas: Part 1

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.

<canvas id="yourCanvas" width="300" height="150">
     I'm sorry you're browser doesn't seem to support Canvas at this time.

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:

     var canvas = document.getElementById('myCanvas');

Then you can specify the context (ctx for short):

     var canvas = document.getElementById('myCanvas');
         ctx = canvas.getContext('2d');

Now let’s build a simple rectangle after our context variable:

     var canvas = document.getElementById('myCanvas');
         ctx = canvas.getContext('2d');
     ctx.fillRect(0, 0, 150, 100);

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:

ctx.fillStyle = '#CCCCCC';
ctx.strokeStyle = '#000000';
ctx.lineWidth = 2;

Now let’s create our boxes:

ctx.fillRect (0, 0, 150, 50);
ctx.strokeRect(0, 60, 150, 50);
ctx.clearRect (30, 25, 90, 60);
ctx.strokeRect(30, 25, 90, 60);


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:

ctx.arc(75, 75, 50, 0, Math.PI*2, true);

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:

ctx.fillStyle = '#FF1C0A'
ctx.arc(75, 75, 50, 0, Math.PI*2, true);

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.

ctx.lineWidth = 4;
ctx.moveTo(50, 100);
ctx.quadraticCurveTo(250, 50, 450, 150);
    //(quadraticCurveTo(cpx, cpy, x, y);)

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);


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’.
Source Developer Drive

About ReadWrite’s Editorial Process

The ReadWrite Editorial policy involves closely monitoring the tech industry for major developments, new product launches, AI breakthroughs, video game releases and other newsworthy events. Editors assign relevant stories to staff writers or freelance contributors with expertise in each particular topic area. Before publication, articles go through a rigorous round of editing for accuracy, clarity, and to ensure adherence to ReadWrite's style guidelines.

Get the biggest tech headlines of the day delivered to your inbox

    By signing up, you agree to our Terms and Privacy Policy. Unsubscribe anytime.

    Tech News

    Explore the latest in tech with our Tech News. We cut through the noise for concise, relevant updates, keeping you informed about the rapidly evolving tech landscape with curated content that separates signal from noise.

    In-Depth Tech Stories

    Explore tech impact in In-Depth Stories. Narrative data journalism offers comprehensive analyses, revealing stories behind data. Understand industry trends for a deeper perspective on tech's intricate relationships with society.

    Expert Reviews

    Empower decisions with Expert Reviews, merging industry expertise and insightful analysis. Delve into tech intricacies, get the best deals, and stay ahead with our trustworthy guide to navigating the ever-changing tech market.