Wednesday, March 21, 2012

Canvas Size || HTML5 Canvas Tutorial 2

In this tutorial I will show you how to re-size your canvas.  This tutorial assumes that you have read the first tutorial in this series (HTML5 Canvas Tutorial 1) or have basic knowledge of how to add a canvas element.

How to Re-Size Your Canvas

Re-sizing a canvas is pretty simple, you only need to add two attributes to your canvas tag, but first we need to make sure you have a canvas to add these attributes to.
<!DOCTYPE HTML>
<html>
    <head>
        <title>
            HTML5 Canvas Tutorial
        </title>
        <style type="text/css">
            #myCanvas {
                border:1px solid #000000;
            }
        </style>
    </head>
    <body>
        <canvas id="myCanvas"></canvas>
    </body>
</html>
If you did the previous tutorial this code should look familiar.  This code declares a HTML5 document, adds a canvas element to the page, and gives that element a black border to make it more visible.  If you were to view this document in your web-browser it should look like this.

Now if we wanted to change the width of the canvas to 500 pixels wide we need to add the attribute width="500" to our opening canvas tag.
        <canvas id="myCanvas" width="500"></canvas>
 If you view this in your browser, you should get something that looks like this.


Changing the height works the exact same way.  For example if you wanted a height of 300 pixels, simply add height="300".
        <canvas id="myCanvas" width="500" height="300"></canvas> 
Your document should now look like this in your browser.


Finished Code
<!DOCTYPE HTML>
<html>
    <head>
        <title>
            HTML5 Canvas Tutorial
        </title>
        <style type="text/css">
            #myCanvas {
                border:1px solid #000000;
            }
        </style>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="300"></canvas>
    </body>
</html>

No comments:

Post a Comment