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
<!--[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. </canvas>
<script> var canvas = document.getElementById('myCanvas'); </script>
Then you can specify the context (ctx for short):
<script> var canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); </script>
Now let’s build a simple rectangle after our context variable:
<script> var canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 150, 100); </script>
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.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI*2, true); ctx.closePath(); ctx.fill();
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.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI*2, true); ctx.closePath(); ctx.fill();
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.beginPath(); ctx.moveTo(50, 100); ctx.quadraticCurveTo(250, 50, 450, 150); //(quadraticCurveTo(cpx, cpy, x, y);) ctx.srtoke();
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);
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’.